Combining two lists into a list of lists

I have two lists:

a = ['1', '2']
b = ['11', '22', '33', '44']

And I have to combine them to create a list like the one below:

op = [('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

How could I achieve this?

+4
source share
2 answers

You want itertools.zip_longest with fillvaluean empty line:

a = ['1', '2']
b = ['11', '22', '33', '44']

from itertools import zip_longest # izip_longest for python2

print(list(zip_longest(a,b, fillvalue="")))
[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

For python2, this is izip_longest :

from itertools import izip_longest 

print(list(izip_longest(a,b, fillvalue="")))
[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

If you just want to use the values, you can iterate over the izip object:

for i,j  in izip_longest(a,b, fillvalue=""):
   # do whatever

Some timings and map usage:

In [51]: a = a * 10000

In [52]: b = b * 9000

In [53]: timeit list(izip_longest(a,b,fillvalue=""))
100 loops, best of 3: 1.91 ms per loop

In [54]: timeit [('', i[1]) if i[0] == None else i  for i in map(None, a, b)]
100 loops, best of 3: 6.98 ms per loop

map also creates another list using python2, so for large lists or if you have memory limitations, it is better to avoid.

+9
source

In Python 2.7: another way to do this:

[('', i[1]) if i[0] == None else i for i in map(None, a, b)]

, izip_longest:

>>> timeit.timeit("[('', i[1]) if i[0] == None else i  for i in map(None, a, b)]", 'from __main__ import a, b')
1.3226220607757568

>>> timeit.timeit("list(itertools.izip_longest(a, b, fillvalue=''))", 'from __main__ import a, b')
1.629504919052124

, '', izip_longest .

, , None, '', : map(None, a, b). izip_ilongest .

, , , . , zip , SO " `zip` ` zip_longest`" .

-1

Source: https://habr.com/ru/post/1584538/


All Articles