python - 从列表中获取元素,循环方式

标签 python list iteration

我想从列表的列表中构造一个列表,循环方式。
所有第一个元素,然后所有第二个元素等等。
列表的大小不同。

[[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/

相关文章:

python - 根据指定列中的字符串值条目是否包含子字符串来分隔 pandas 数据框

java - 非法参数异常 : 'Unsupported class file major version 55'

python - 计算两个日期之间的年+月+天?

python - 在Python的列表中使用min函数获取AttributeError

java - MongoDB Java驱动程序: distinct and iterative

python - 如何将 tqdm 控制台输出记录到 Python 中的文件中?

list - 在OCaml中,为什么列表构造函数::不是运算符

javascript - 为什么属性值为 "undefined"?

python - 用于数独解题器的从水平行列表中获取部分的一种简短(呃)方法

list - VBScript 中的哪种列表类型允许插入和删除元素?