Question

This works nicely:

In [53]: map(None, a,c,d)
Out[53]: [(1, 4, 'a'), (2, 5, 'b'), (3, 6, None), (None, 7, None)]

(

In [60]: a
Out[60]: [1, 2, 3]

In [61]: c
Out[61]: [4, 5, 6, 7]

In [62]: d
Out[62]: ['a', 'b']

)

But if I want lists instead of tuples it fails:

In [54]: map(list, a,c,d)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-9447da50383e> in <module>()
----> 1 map(list, a,c,d)

TypeError: list() takes at most 1 argument (3 given)

I can get around this by:

In [58]: [list(x) for x in map(None, a, c, d)]
Out[58]: [[1, 4, 'a'], [2, 5, 'b'], [3, 6, None], [None, 7, None]]

But is there smth that I could use in map() directly?

It seems that most sequences have this problem:

In [59]: tuple(3,3,5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-59-f396cf5fe9be> in <module>()
----> 1 tuple(3,3,5)

TypeError: tuple() takes at most 1 argument (3 given)   

I'd like to be able to pass a peculiar sequence to map() and get a list of such sequences (such as lists, sets, etc) combining subsequent elems from "zipped" (mapped) sequences.

Was it helpful?

Solution

>>> from itertools import izip_longest
>>> [list(x) for x in itertools.izip_longest([1,2,3],[4,5,6,7],['a','b'])]
[[1, 4, 'a'], [2, 5, 'b'], [3, 6, None], [None, 7, None]]

OTHER TIPS

You usually use the zip() function to zip lists; your use of map() is a happy side-effect of how that function works.

zip() still produces tuples, but you can combine that with map():

map(list, zip(a, c, d))

or you can use a list comprehension (slower but more flexibility when filtering, nesting loops and transforming the data):

[list(t) for t in zip(a, c, d)]

Use

map(list, map(None, a, c, d))  

Since map(None, ...) is equivalent to itertools.izip_longest(...)..
This is better (in 2.x at least) :

map(list, itertools.izip_longest(a, c, d))

Here are some examples..

In [100]: zip(a,c,d)
Out[100]: [(1, 4, 'a'), (2, 5, 'b')]

In [101]: map(None, a,c,d)
Out[101]:[(1, 4, 'a'), (2, 5, 'b'), (3, 6, None), (None, 7, None)]

In [102]: map(list, map(None, a,c,d))
Out[102]:[[1, 4, 'a'], [2, 5, 'b'], [3, 6, None], [None, 7, None]]

In [103]: import itertools
In [104]: map(list, itertools.izip_longest(a,c,d))
Out[104]:[[1, 4, 'a'], [2, 5, 'b'], [3, 6, None], [None, 7, None]]

Also, it seems you don't understand how to use tuple & list:
These 2 function-like objects take an iterable and convert them to a tuple & list respectively.

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> list(tuple(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top