![](/img/trans.png)
[英]Creating a new list based on matching elements of two nested lists in Python?
[英]Create new list based on ordered elements of two lists
我有兩個列表,想根據列表的每個元素創建一個新列表。
list1 = [23, 57, 223, 246, 286, 429]
list2 = [17, 138, 425, 680, 535, 1063]
我想要新列表,例如:
list3 = [23, 17, 57, 138, 223, 425]
這是
list3 = [list1[0], list2[0], list1[1], list2[1], ...]
我該如何進行。 我知道 append 不起作用,zip 也不起作用。
您可以使用itertools.chain
來展平zip
的輸出:
from itertools import chain
list3 = [*chain(*zip(list1, list2))]
或者更簡單的嵌套理解:
list3 = [x for pair in zip(list1, list2) for x in pair]
如果您只需要輸入列表的一部分,只需使用適當的切片:
list3 = [*chain(*zip(list1[:3], list2))]
您可以使用 double for
循環。 一個迭代壓縮的元組,一個迭代元組的元素:
x=[k for j in zip(list1,list2) for k in j]
嘗試單行是很好的,但這確實意味着閱讀它的人(包括幾個月后的你)將不得不坐在那里完成它的工作。
以稍微冗長的方式進行操作可能會更直接易讀:
out = []
for x in zip(list1, list2):
out.extend(x)
list1= [23, 57, 223, 246, 286, 429]
list2= [17, 138, 425, 680, 535, 1063]
list3 = []
x = zip(list1,list2)
for i in list(x):
i = list(i)
list3.append(i)
print(list3)
循環遍歷列表的索引並同時從兩個列表中添加元素以得到結果
list1 = [23, 57, 223, 246, 286, 429]
list2 = [17, 138, 425, 680, 535, 1063]
result = []
for i in range(0,len(list1)):
result.append(list1[i])
result.append(list2[i])
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.