所以,我在看 Raymond Hettinger 的演讲 Transforming Code into Beautiful, Idiomatic Python他提出了这种我从未意识到的iter
形式。他的例子如下:
代替:
blocks = []
while True:
block = f.read(32)
if block == '':
break
blocks.append(block)
使用:
blocks = []
read_block = partial(f.read, 32)
for block in iter(read_block, ''):
blocks.append(block)
检查 documentation 后iter
,我发现了一个类似的例子:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
这对我来说看起来很有用,但我想知道你们中的 Pythonistas 是否知道不涉及 I/O 读取循环的这种构造的任何示例?也许在标准库中?
我能想到非常人为的例子,如下所示:
>>> def f():
... f.count += 1
... return f.count
...
>>> f.count = 0
>>> list(iter(f,20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
但显然这并不比内置的可迭代对象更有用。此外,当您将状态分配给函数时,我觉得代码有味道。那时,我可能应该使用一个类,但如果我要编写一个类,我也可以为我想完成的任何事情实现迭代器协议(protocol)。
最佳答案
这是我想出的一个愚蠢的例子:
from functools import partial
from random import randint
pull_trigger = partial(randint, 1, 6)
print('Starting a game of Russian Roulette...')
print('--------------------------------------')
for i in iter(pull_trigger, 6):
print('I am still alive, selected', i)
print('Oops, game over, I am dead! :(')
示例输出:
$ python3 roulette.py
Starting a game of Russian Roulette...
--------------------------------------
I am still alive, selected 2
I am still alive, selected 4
I am still alive, selected 2
I am still alive, selected 5
Oops, game over, I am dead! :(
我们的想法是拥有一个生成随机值的生成器,并且您希望在选择了特定值后进行处理。你可以例如在尝试确定随机过程的平均结果的每次模拟运行中使用此模式。
当然,您要建模的过程在幕后可能比简单的掷骰子复杂得多...
我能想到的另一个例子是重复执行一个操作,直到它成功,由一个空的错误消息指示(我们在这里假设一些第 3 方函数是这样设计的,而不是例如使用异常):
from foo_lib import guess_password
for msg in iter(guess_password, ''):
print('Incorrect attempt, details:', msg)
# protection cracked, continue...
关于python - iter(callable, sentinel)有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38087427/