在Python3中,如何将列表中的元素放到列表中?
我试图将在Python3中,如何将列表中的元素放到列表中?,python,python-3.x,algorithm,list,nested,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,
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]
[list_1[idx] + [x] for idx, x in enumerate(list_2)]
> [[0, 1, 100], [1, 4, 100], [2, 3, 100]]
例:
输出:
[[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]]
这将变异
列表\u 1
。。。我怀疑OP是在store_1=[[[*l1,l2]之后的,对于zip中的l1,l2(list_1,list_2)]