Pregunta

Is there a way to apply izip_longest() to lists inside a list?

If I have

somelist = [[1, 2, 3], "abcd", (4, 5, 6)]

is there a way to do

izip_longest(somelist[0], somelist[1], ....)
¿Fue útil?

Solución

You can unpack the list, with the *, like this

my_list = [[1, 2, 3], "abcd", (4, 5, 6)]
izip_longest(*my_list)

For example,

from itertools import izip_longest

my_list = [[1, 2, 3], "abcd", (4, 5, 6)]
print list(izip_longest(*my_list))

Output

[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6), (None, 'd', None)]

Note: Using list as a variable name will shadow the builtin list function

If you choose to use a custom replacement value instead of None, you can do it like this

print list(izip_longest(*my_list, fillvalue = -1))

Output

[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6), (-1, 'd', -1)]

Otros consejos

Use the *args calling syntax:

some_list = [[1, 2, 3], "abcd", (4, 5, 6)]
izip_longest(*somelist)

This syntax applies all elements of somelist as separate arguments to the called object.

This applies to all calls, not just izip_longest().

Demo:

>>> from itertools import izip_longest
>>> some_list = [[1, 2, 3], "abcd", (4, 5, 6)]
>>> list(izip_longest(*some_list))
[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6), (None, 'd', None)]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top