[英]Combine numerous lists of different length in python in an alternating order
如果我有一些清單
我可以將列表1與列表2合並,但是,我還沒有成功地將其他列表合並。
def alternator():
iets = []
for i in range(len(list2)):
something += [list1[i]]
something +=[list2[i]]
result = something
result_weaver(result)
def result(x):
list31 = list3
if len(list3) < len(x) :
while len(list31) != len(x):
list31 += '-'
我決定添加“-”,以確保兩個列表的長度相等,因此for循環可以正常工作。
有誰對如何編程有更好的主意嗎?
在此處使用itertools.zip_longest()
:
try:
from itertools import zip_longest
except ImportError:
# Python 2
from itertools import izip_longest as zip_longest
def alternate(list1, list2):
return [v for v in sum(zip_longest(list1, list2), ()) if v is not None]
zip_longest()
調用添加None
占位符(類似於您自己嘗試添加-
字符),我們需要在壓縮后再次從sum()
輸出中刪除該占位符。
演示:
>>> alternate(list1, list2)
['1', '5', '2', '6', '3', '7', '8']
>>> alternate(alternate(list1, list2), list3)
['1', '9', '5', '2', '6', '3', '7', '8']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.