[英]Call function in loop line and store return value to variable to then be used in the loop?
I want to do something like the following: 我想做类似以下的事情:
while myFunc() as myVar:
print myVar
Basically, just call a function in the loop line that will return a value and continue the loop depending on that value, but I would also like to be able to use that value within the loop and I would rather not have to call the function a 2nd time. 基本上,只需在循环行中调用一个函数,该函数将返回一个值并根据该值继续循环,但我也希望能够在循环中使用该值,而我宁愿不必调用函数第二次。
What I would like to avoid: 我想避免的:
while myFunc():
myVar = myFunc()
print myVar
You can accomplish this using the two-argument version of the iter()
built-in function: 您可以使用
iter()
内置函数的双参数版本来完成此操作:
for myVar in iter(myFunc, sentinel):
print myVar
This is equivalent to the following: 这相当于以下内容:
while True:
myVar = myFunc()
if myVar == sentinel:
break
print myVar
From the docs for iter()
: 来自
iter()
的文档:
If the second argument, sentinel , is given, then o must be a callable object.
如果给出第二个参数sentinel ,则o必须是可调用对象。 The iterator created in this case will call o with no arguments for each call to its
next()
method;在这种情况下创建的迭代器将为每个对
next()
方法的调用调用o而不带参数; if the value returned is equal to sentinel,StopIteration
will be raised, otherwise the value will be returned.如果返回的值等于sentinel,则会引发
StopIteration
,否则返回该值。
Use a generator that returns that value. 使用返回该值的生成器。
for myVal in myFunc():
print myVal
This is in combination of the yield statement. 这是yield语句的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.