给定一个list和一个2d-list(长度可能相同,也可能不相同)
list1 = [1,2,3,4]
list2 = [1,2]
table = [[1,2,0],
[3,4,1],
[4,4,4]]
我想将列表作为列附加到2d-list,充分管理空值。
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
。我在想,这可能是一个好主意,pivot表,然后只是追加一行和pivot返回,但我不能得到这个想法来处理适当的大小问题。
使用生成器函数和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]]
这个怎么样?
table = [column + [list1[i] if i < len(list1) else None] for i, column in enumerate(list1)]