python - 创建迭代器以从每个可迭代对象中一一返回元素
问题描述
我正在学习 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 上搜索了一个解决方案,但没有找到。
解决方案
您可以使用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]
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))
推荐阅读
- esp32 - esp smartconfig 发生了什么,在 v4.1 中是一团糟?
- python - 如何在 Python 中创建一个有效的函数来填充因子 (t+1)
- bash - 即使在 If 块中,Makefile 也会引发错误
- javascript - if 语句在 for 循环中如何工作?
- python-3.x - 为多个 PDF 运行 Python pgm
- python-3.x - 管理两个不同版本的 Python
- snowflake-cloud-data-platform - 如何在雪花中生成两张表的笛卡尔积?
- java - 如何覆盖使用原始类型的方法?
- python - 以这样一种方式合并列,即具有重复元素的行用逗号分隔
- python-3.x - 为什么 message.channel.send() 在这里不起作用?