迭代不同长度列表中的所有列表

问题描述

我有一个列表列表.它看起来像这样:

I have a list of lists. It looks something like this:

[
    [4,7,9,10],
    [5,14,55,24,121,56, 89,456, 678],
    [100, 23, 443, 34, 1243,]
    ....
]

我想进行迭代,以便在每次迭代时从所有列表中获取该索引的相应元素,如果列表为空,则将其删除.

I want to iterate such that on every iteration I get the respective element of that index from all lists and if the list gets empty, drop it.

例如,当索引为 0 时,我想要一个列表,该列表将从列表 0 中扩展(添加)4,从列表 1 中扩展(添加)5,从列表 2 中扩展(添加)100(所有列表的第 0 个索引)并且如果列表为空(像列表 0 在第 3 次迭代后将被完全覆盖,跳过它.所以迭代应该跳过这个列表并移动到下一个列表.

For instance, when index will be 0, I want a list that would extend (add) 4 from list 0,5 from list 1, 100 from list 2 (0th index of all list) and if the list gets empty (like list 0 will be fully covered after 3rd iteration, skip it. So iteration should skip this list and move on the next list.

所以输出应该是这样的:[4,5,100, 7, 14, 23, 9, 55, 443, 10, 24, 34, 121, 1243, 56. 89, 456, 678]

So the output should look like: [4,5,100, 7, 14, 23, 9, 55, 443, 10, 24, 34, 121, 1243, 56. 89, 456, 678]

我想要一个扩展这些值的列表.

I want a list that extends these values.


解决方案

zip_longest 是有问题的,因为如果 fillvalue 出现在输入(这可以解决,但它总是会有点hacky).

zip_longest is problematic, since any solution would silently drop the fillvalue if it occurs in the inputs (this can be worked around, but it's always going to be a little hacky).

最通用的解决方案是 roundrobin 配方noreferrer">itertools 模块:

The most general solution is the roundrobin recipe from the itertools module:

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))

对于您的输入,您可以执行以下操作:

For your input, you'd do something like:

mylist = [
    [4,7,9,10],
    [5,14,55,24,121,56, 89,456, 678],
    [100, 23, 443, 34, 1243,]
    ....
]    

print(list(roundrobin(*mylist)))

相关文章