从列表中获取元素,轮循样式 [英] Take elements from lists, round robin style
本文介绍了从列表中获取元素,轮循样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以循环方式从列表列表构建列表.
所有第一个元素,然后所有第二个元素,等等.
列表的大小不一样.
I want to construct a list from a list of lists, round robin style.
All first elements, then all second elements etc.
The lists aren't the same size.
[[1, 2, 3], [4, 5], [6], [], [7, 8, 9, 10]]
应转到:
[1, 4, 6, 7, 2, 5, 8, 3, 9, 10]
.
推荐答案
您可以使用轮询食谱(来自itertools):
You can use the roundrobin recipe from 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) # .next on Python 2
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))
输出:
l = [[1,2,3],[4,5],[6],[],[7,8,9,10]]
print(list(roundrobin(*l)))
[1, 4, 6, 7, 2, 5, 8, 3, 9, 10]
这篇关于从列表中获取元素,轮循样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文