繁体   English   中英

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

[英]How to put elements from a list to a list of list in Python 3?

我正在尝试将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]]

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

使用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]]

不使用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]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM