如何在2D列表中插入列表?

时间:2014-06-18 21:55:59

标签: python arrays list multidimensional-array

给出一个列表和一个二维列表(可能是也可能不是相同的长度)

list1 = [1,2,3,4]

list2 = [1,2]

table = [[1,2,0],
         [3,4,1],
         [4,4,4]]

我想将列表作为列附加到2d列表,充分管理空值。

result1 = [[1,2,0,         1],
           [3,4,1,         2],
           [4,4,4,         3],
           [None,None,None,4]]

result2 = [[1,2,0,   1],
           [3,4,1,   2],
           [4,4,4,None]]

这是我到目前为止所拥有的:

table = [column + [list1[0]] for column in table]

但是我使用迭代器代替0来解决语法问题。

我在想这样的事情:

table = [column + [list1[i]] for column in enumerate(table,i)]

但我得到一个元组连接到元组TypeError。我当时认为转动表格然后只需追加一行并向后转动可能是一个好主意,但我无法理解这个问题来适当地处理尺寸问题。

2 个答案:

答案 0 :(得分:1)

使用生成器函数和itertools.izip_longest

from itertools import izip_longest

def add_column(lst, col):

    #create the list col, append None's if the length is less than table's length
    col = col + [None] * (len(lst)- len(col))

    for x, y in izip_longest(lst, col):
        # here the if-condition will run only when items in col are greater than 
        # the length of table list, i.e prepend None's in this case.
        if x is None:
            yield [None] *(len(lst[0])) + [y] 
        else:
            yield x + [y]            


print list(add_column(table, list1))
#[[1, 2, 0, 1], [3, 4, 1, 2], [4, 4, 4, 3], [None, None, None, 4]]
print list(add_column(table, list2))
#[[1, 2, 0, 1], [3, 4, 1, 2], [4, 4, 4, None]]

答案 1 :(得分:0)

这个怎么样?

table = [column + [list1[i] if i < len(list1) else None] for i, column in enumerate(list1)]