Python 在生成器中有一个很酷的特性——它们允许您轻松地生成与for
循环一起使用的迭代器,这可以简化这种代码。
def input_until(message, func):
"""Take raw input from the user (asking with the given message), until
when func is applied it returns True."""
while True:
value = raw_input(message)
if func(value):
return
else:
yield value
for value in input_until("enter input: ", lambda x: x == "exit"):
...
循环将for
一直循环,直到迭代器停止,当用户输入时我们创建的迭代器停止"exit"
。请注意,我已经对此进行了一些概括,为简单起见,您可以将检查硬编码"exit"
到生成器中,但如果您在一些地方需要类似的行为,则可能值得保持通用。
请注意,这也意味着您可以在列表推导中使用它,从而也可以轻松构建结果列表。
编辑:或者,我们可以使用以下方式构建它itertools
:
def call_repeatedly(func, *args, **kwargs):
while True:
yield func(*args, **kwargs)
for value in itertools.takewhile(lambda x: x != "exit",
call_repeatedly(raw_input, "enter input: ")):
...