简体   繁体   English

在循环行中调用函数并将返回值存储到变量然后在循环中使用?

[英]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.

相关问题 如何将函数的返回值存储到变量中,然后在while循环中使用它? - How to store return value of function into a variable and subsequently use it in while loop? 将带有循环的函数的结果存储在变量中 - Store the result of a function with loop in a variable 有没有办法在for循环中更改函数中使用的变量? - Is there a way to change the variable used in a function while in a for loop? 将 for 循环迭代的值存储到单个变量中(Python) - store value of for loop iteration into single variable (Python) 在循环内调用函数,但无法返回结果 - Call a function inside a loop, but cannot return the results Python循环调用同一个function,并以最后一次调用的返回值作为本次调用的参数 - Python calls the same function in a loop, and uses the return value of the last call as the parameter of this call For 循环将结果存储在变量中 - For loop store outcome in variable 如果它有返回值,则循环遍历 python 函数 - Loop over a python function if it has a return value Function 返回,for循环只返回1个值 - Function return, only returns 1 value on for loop 在循环中动态调用和打印函数的返回值,覆盖以前的输出 - Dynamically call and print a function's return-value within a loop, overwrite previous outputs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM