在python中将列表元素附加到列表列表中
鉴于以下清单:在python中将列表元素附加到列表列表中,python,list,python-3.x,append,Python,List,Python 3.x,Append,鉴于以下清单: list1 = [[1, 2], [3, 4], [5, 6], [7, 8]] list2 = [10, 11, 12, 13] 更改list1以使其成为python中的以下列表的最佳方法是什么 [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]] 您可以使用zip: [x + [y] for x, y in zip(list1, list2)] # [[1, 2, 10
list1 = [[1, 2],
[3, 4],
[5, 6],
[7, 8]]
list2 = [10, 11, 12, 13]
更改list1
以使其成为python中的以下列表的最佳方法是什么
[[1, 2, 10],
[3, 4, 11],
[5, 6, 12],
[7, 8, 13]]
您可以使用
zip
:
[x + [y] for x, y in zip(list1, list2)]
# [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
要就地修改列表1,您可以执行以下操作:
for x, y in zip(list1, list2):
x.append(y)
list1
# [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
或者,如果您使用的是Python>=3.5,则在
zip
ing之后理解解包:
>>> l = [[*i, j] for i,j in zip(list1, list2)]
>>> print(l)
[[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
当然,如果列表大小可能不同,最好使用来优雅地处理额外的元素 您可以这样做:
list1 = [[1, 2],
[3, 4],
[5, 6],
[7, 8]]
list2 = [10, 11, 12, 13]
def add_item_to_list_of_lists(list11, list2):
# list1, list to add item of the second list to
# list2, list with items to add to the first one
for numlist, each_list in enumerate(list1):
each_list.append(list2[numlist])
add_item_to_list_of_lists(list1, list2)
print(list1)
输出
[[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]
你为什么要提供?它们的内容应该是注释吗?为什么要使用
list1[numlist]
而不是每个列表
?