如何将列表作为列插入二维列表中?

2 投票
2 回答
696 浏览
提问于 2025-04-18 10:17

给定一个列表和一个二维列表(它们的长度可能相同,也可能不同)

list1 = [1,2,3,4]

list2 = [1,2]

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

我想把这个列表作为一列添加到二维列表中,同时妥善处理空值。

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

那这个呢?

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

使用生成器函数和 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]]

撰写回答