我有4个列表:
a = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"]
b = ["b1", "b2", "b3", "b4", "b5", "b6"]
c = ["c1", "c2", "c3", "c4", "c5"]
d = ["d1", "d2", "d3", "d4", "d5", "d6", "d7"]
我需要创建一个列表,一个接一个地交替元素,直到可能,但是对于最后一个列表,我需要将它们2乘2(也直到可能)。所以结果应该是:
new_list = ["a1", "b1", "c1", "d1", "d2", "a2", "b2", "c2", "d3", "d4", "a3", "b3",
"c3", "d5", "d6", "a4", "b4", "c4", "d7", "a5", "b5", "c5", "a6", "b6",
"a7", "a8"]
我知道你可以使用itertools,比如:
import itertools
book_list = [x for x in itertools.chain.from_iterable(itertools.zip_longest(a,b, c, d)) if x is not None]
但是我要确保list d取2个元素而不是1个吗?我可以在列表d中引入一对()吗?
您可以从d
和zip
中创建一个迭代器,每次迭代从序列中提取两次:
d2 = iter(d)
new_list = list(filter(None, chain.from_iterable(zip_longest(a, b, c, d2, d2))))
演示:https://replit.com/@blhsing/MarriedOrderlyPoint
我实际上通过将列表d分成两个列表来简单地解决了这个问题,一个包含偶数元素,另一个包含奇数元素。
d_even = d[0::2]
d_odds = d[1::2]
然后添加到zip:
new_list = list(filter(None, chain.from_iterable(zip_longest(a, b, c, d_even, d_odd))))