alternative to zip(*map(f, lst))?
Alex Martelli
aleax at aleax.it
Tue Jan 22 15:20:00 EST 2002
Huaiyu Zhu wrote:
...
>>>> def f(x): return x, x*3
> ...
>>>> a, b = zip(*map(f, range(2))); print a, b
> (0, 1) (0, 3)
>>>> a, b = zip(*map(f, range(1))); print a, b
> (0,) (0,)
>>>> a, b = zip(*map(f, range(0))); print a, b
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: zip() requires at least one sequence
>
> Is is possible to get () () in the last case? Thanks.
Possible, and even quite easy, although not necessarily
good programming practice:
a, b = n and zip(*map(f, range(n))) or 2*[()]
more generally, for an arbitrary sequence X and f
returning an N-tuple for an arbitrary given N,
X and zip(*map(f, X)) or N*[()]
However, as I mentioned, I don't think that building such
"deep" (as in "complicated") inline expressions is best
programming practice. You don't get a prize for squishing
everything into one expression. I would code, NOT
def hz(f, X, N): return X and zip(*map(f, X)) or N*[()]
but rather:
def am(f, X, N):
if X: return zip(*map(f, X))
else: return N*[()]
(assuming for the sake of argument that I did want to
use the zip(*map trick at all, of course:-).
Alex
More information about the Python-list
mailing list