简体   繁体   English

合并两个长度不等的2D列表以创建一个新列表

[英]Combine two 2D Lists of unequal length to create one new list

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. 我有两个长度不等的2D列表,我想将两者合并为一个2D列表,当其中一个父列表不足时,我希望将循环放在一个空格中。

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 : 使用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, '', '']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM