[英]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.