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

标签 python arrays list multidimensional-array

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

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。我认为旋转表格然后添加一行并向后旋转可能是个好主意,但我无法正确处理大小问题。

最佳答案

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

关于python - 如何将列表作为二维列表中的列插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295656/

相关文章:

c - 在 C 中将字符串存储在 char 数组中——我做错了什么?

arrays - 如何将十六进制字符串转换为字节数组?

Java - 在元素随机化后恢复列表的原始顺序

python - 尝试 except 语句 python

python - 如何将 int 导出到 "txt"文件,然后在以后能够将它们作为 int 导入回来

C 程序数组需要的输入比应有的多

c - 增加意外错误

c - 使用链表排序

Python否定 bool 函数

python - Hortonworks 中的 Apache kafka 错误