【问题标题】:Combine two 2D Lists of unequal length to create one new list合并两个长度不等的二维列表以创建一个新列表
【发布时间】:2013-07-08 11:47:26
【问题描述】:

我有两个长度不等的 2D 列表,我希望将两者组合成一个 2D 列表,当其中一个父列表不足时,我希望循环放入一个空格。

例如:

list1 = [['abc',123],['def',456],['ghi',789]]
list2 = [['abc',123],['def',456]]

期望的结果:

list3 = [['abc',123,'abc',123],['def',456,'def,456],['ghi',789,'','']]

我一直在尝试使用循环来计算递归并将其用作列表索引(如下),但这限制了最短列表的方法,我最终会丢失数据。

list3 = list1[count]+list2[count]

【问题讨论】:

    标签: python list multidimensional-array nested-lists


    【解决方案1】:

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

    【讨论】:

    • 完美!谢谢,关于python模块的知识还有很多,时间用完我会接受你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多