I've got two 2D lists of unequal length and I'm looking to combine the two into one 2D list, when one of the parent lists falls short I'd like the loop to put in a space.
For example:
list1 = [['abc',123],['def',456],['ghi',789]]
list2 = [['abc',123],['def',456]]
Desired outcome:
list3 = [['abc',123,'abc',123],['def',456,'def,456],['ghi',789,'','']]
I've been trying with loops whereby they count the recursions and use those as the list indexes(below), but this limits the approach to the shortest list and I end up loosing data.
list3 = list1[count]+list2[count]
Use itertools.izip_longest
:
>>> from itertools import izip_longest
>>> [x+y for x,y in izip_longest(list1,list2, fillvalue = ['',''])]
[['abc', 123, 'abc', 123], ['def', 456, 'def', 456], ['ghi', 789, '', '']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.