如何在Python 3中将元素从列表放到列表中?

时间:2019-03-19 13:23:36

标签: python python-3.x algorithm list nested

我试图将list2中的元素放入list1中的每个嵌套列表中。到目前为止,这是我尝试过的:

list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
store_1 = []
for x in list_1:
    for y in list_2:
        x.append(y)
        store_1.append(x)
print(store_1)

但是输出是:

[[0, 1, 100, 100, 100], [0, 1, 100, 100, 100], [0, 1, 100, 100, 100], [1, 4, 100, 100, 100], [1, 4, 100, 100, 100], [1, 4, 100, 100, 100], [2, 3, 100, 100, 100], [2, 3, 100, 100, 100], [2, 3, 100, 100, 100]]

输出应如下所示:

[[0,1,100],[1,4,100], [2,3,100]]

如何修复代码以获得所需的输出?

2 个答案:

答案 0 :(得分:5)

使用zip

例如:

list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
store_1 = [x + [y] for x, y in zip(list_1, list_2)]
print(store_1)

输出:

[[0, 1, 100], [1, 4, 100], [2, 3, 100]]

答案 1 :(得分:1)

不使用zip

list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
[list_1[idx] + [x] for idx, x in enumerate(list_2)]

> [[0, 1, 100], [1, 4, 100], [2, 3, 100]]