3 回答

TA贡献1828条经验 获得超3个赞
您可以zip
一起使用chain.from_iterable
:
list(chain.from_iterable(zip(list1, list2)))
示例:
from itertools import chain
list1 = [['a',1],['b',2],['c',3],['d',4]]
list2 = [['e',5],['f',6],['g',7],['h',8]]
print(list(chain.from_iterable(zip(list1, list2))))
# [['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]

TA贡献1812条经验 获得超5个赞
只需itertools.chain
使用zip
:
>>> import itertools
>>> list(itertools.chain(*zip(list1, list2)))
[['a', 1], ['e', 5], ['b', 2], ['f', 6], ['c', 3], ['g', 7], ['d', 4], ['h', 8]]

TA贡献1725条经验 获得超7个赞
最通用的解决方案是模块roundrobin
中的配方:itertools
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
list1 = [['a',1],['b',2],['c',3],['d',4]]
list2 = [['e',5],['f',6],['g',7],['h',8]]
print(list(roundrobin(list1, list2)))
产生你想要的输出。
chain与+不同zip,此解决方案适用于不均匀长度的输入,其中zip将静默丢弃超出最短输入长度的所有元素。
添加回答
举报