首页 > 解决方案 > 创建迭代器以从每个可迭代对象中一一返回元素

问题描述

我正在学习 itertools 模块,我正在尝试制作一个迭代器来从作为输入提供的可迭代对象中返回每个元素。

Agruments   Results
p, q, …     p0, q0, … plast, qlast 

还有一个骑手,如果说列表的长度不同,那么next(it)当较短的列表用完时,应该从较长的列表中返回元素。

尝试解决

import itertools
l1=[1,2,3,4,5,6]
l2=['a','b','c','d']
l=[]
for x,y in itertools.zip_longest(l1,l2):
    l.extend([x,y])
it=iter(x for x in l if x is not None)

哪种解决了我的问题

print(list(it))

输出:

[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 6]

有没有更简单或更好的方法来做到这一点?我在 SO 上搜索了一个解决方案,但没有找到。

标签: pythonpython-3.xitertools

解决方案


您可以使用itertools.chain.from_iterable()来展平序列,并使用生成器表达式来过滤掉None值:

from itertools import chain, zip_longest

it = (v for v in chain.from_iterable(zip_longest(l1, l2)) if v is not None)

您可能希望使用专用的哨兵,而不是None用作哨兵值,以便可以None在输入列表中使用:

_sentinel = object()
flattened = chain.from_iterable(zip_longest(l1, l2, fillvalue=_sentinel))
it = (v for v in flattened if v is not _sentinel)

如果你想过滤掉虚假,那么你也可以使用filter(None, ...)

it = filter(None, chain.from_iterable(zip_longest(l1, l2)))

演示:

>>> from itertools import chain, zip_longest
>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = ['a', 'b', 'c', 'd']
>>> it = (v for v in chain.from_iterable(zip_longest(l1, l2)) if v is not None)
>>> list(it)
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 6]

并与当地哨兵一起:

>>> l1 = [1, None, 2, None, 3, None]
>>> l2 = ['a', 'b', 'c', 'd']
>>> _sentinel = object()
>>> flattened = chain.from_iterable(zip_longest(l1, l2, fillvalue=_sentinel))
>>> it = (v for v in flattened if v is not _sentinel)
>>> list(it)
[1, 'a', None, 'b', 2, 'c', None, 'd', 3, None]

itertools食谱部分还有:

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

推荐阅读