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

标签 python loops while-loop

我想做如下的事情:

while myFunc() as myVar:
    print myVar

基本上,只需在循环行中调用一个函数,该函数将返回一个值并根据该值继续循环,但我也希望能够在循环中使用该值,我宁愿不必调用第二次执行该功能。

我想避免的事情:

while myFunc():
    myVar = myFunc()
    print myVar

最佳答案

您可以使用 iter() 的双参数版本来完成此操作内置函数:

for myVar in iter(myFunc, sentinel):
    print myVar

这等同于:

while True:
    myVar = myFunc()
    if myVar == sentinel:
        break
    print myVar

来自 iter() 的文档:

If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

关于python - 在循环行中调用函数并将返回值存储到变量中,然后在循环中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14469163/

相关文章:

python - 如何修复 django 1.5 中的 localflavor 弃用警告?

python - 调用句柄后调用recv挂起

java - JAVA如何获取数组重复项的位置

javascript - 如何显示加载百分比以及如何在没有 javascript 的情况下显示加载百分比?

c++ - 二维数组循环显示

javascript - while 循环内的 if 语句。它为什么要这样做?

Java while 循环处理 netbean 错误

python - 通过键入创建 NamedTuple 时引发 TypeError

python - 如何在 Mac (Yosemite) 上找到我的 python/django 源代码

python - for循环中的条件