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))
print(*roundrobin(*lists)) # a 1 w 5 b 2 x 6 c 3 y 7 d 4 z 8
从itertools recipes
itertool recipes建议了一个名为
roundrobin
的解决方案,它允许不同长度的列表。在有切片吗
或者,这里有一个完全依赖切片的解决方案,但是要求所有列表的长度相等。在
^{pr2}$^{} 和^{} :
或者如@PatrickHaugh建议使用^{} :
^{pr2}$如果列表的长度相同,^{} 可用于交错四个列表,就像在您链接的问题中用于交错两个列表一样:
相关问题 更多 >
编程相关推荐