3 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以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貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
只需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貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
最通用的解決方案是模塊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)))
產(chǎn)生你想要的輸出。
chain與+不同zip,此解決方案適用于不均勻長(zhǎng)度的輸入,其中zip將靜默丟棄超出最短輸入長(zhǎng)度的所有元素。
添加回答
舉報(bào)