gpt4 book ai didi

python itertools循环法解释

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:22 27 4
gpt4 key购买 nike

我在 https://more-itertools.readthedocs.io/en/latest/api.html 中看到了循环法的这个代码片段,但我无法理解最后一行 nexts = cycle(islice(nexts, pending)) 如何从 nexts 迭代器中删除耗尽的生成器。据我了解,这会从输入中删除最后一个,但我们不应该删除第一个,即抛出此异常的当前那个吗?

def roundrobin(*iterables):
"""Yields an item from each iterable, alternating between them.

>>> list(roundrobin('ABC', 'D', 'EF'))
['A', 'D', 'E', 'B', 'F', 'C']

This function produces the same output as :func:`interleave_longest`, but
may perform better for some inputs (in particular when the number of
iterables is small).

"""
# Recipe credited to George Sakkis
pending = len(iterables)
if PY2:
nexts = cycle(iter(it).next for it in iterables)
else:
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))

最佳答案

我会一步一步地为你分解:

>>> list(roundrobin('ABC', 'D', 'EF'))


pending = 3 # len(('ABC', 'D', 'EF'))

# nexts roughly equivalent to:
['ABC', 'D', 'EF', 'ABC', 'D', 'EF', 'ABC', ...]

***

# the following get yielded
'A' from 'ABC' # nexts: ['D' , 'EF', 'BC', 'D' , 'EF', ...]
'D' from 'D' # nexts: ['EF', 'BC', '' , 'EF', 'BC', ...]
'E' from 'EF' # nexts: ['BC', '' , 'F' , 'BC', '' , ...]
'B' from 'BC' # nexts: ['' , 'F' , 'C' , '' , 'F' , ...]

# StopIteration was raised by what used to be "B"
SI from '' # nexts: ['F', 'C', '', 'F', 'C', '', 'F', ...]
# ^ index 2 (`pending`[see the following line])

# pending -= 1
pending = 2

# when islice() is used with one argument, it defaults to the "stop" index
# so islice() returns ['F', 'C']
# and cycle() converts it to ['F', 'C', 'F', 'C', ...]

pending = 2
nexts: ['F', 'C', 'F', 'C', ...]

# Go back to *** and continue until pending = 0

这就是最后一行删除耗尽的可迭代对象的方式。


主要思想:

for next in nexts:
yield next()

即使引发了 StopIteration,耗尽的可迭代对象也已从 nexts 中使用。

因此,不要将耗尽的可迭代对象保留为 nexts 中的第一项:

nexts = ['', 'F', 'C', '', 'F', 'C', '', 'F', ...]

nexts的第一项其实就是下一项:

nexts = ['F', 'C', '', 'F', 'C', '', 'F', ...]

关于python itertools循环法解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com