我想从列表的列表中构造一个列表,循环方式。
所有第一个元素,然后所有第二个元素等等。
列表的大小不同。
[[1, 2, 3], [4, 5], [6], [], [7, 8, 9, 10]]
应该转向:
[1, 4, 6, 7, 2, 5, 8, 3, 9, 10]
。
最佳答案
您可以使用循环法 recipe来自 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]
关于python - 从列表中获取元素,循环方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491379/