【问题标题】:Call function in loop line and store return value to variable to then be used in the loop?在循环行中调用函数并将返回值存储到变量然后在循环中使用?
【发布时间】:2013-01-22 22:23:23
【问题描述】:

我想做如下的事情:

while myFunc() as myVar:
    print myVar

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

我想避免的:

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

【问题讨论】:

  • 不,抱歉。您必须找到另一种语言,Python 不会在表达式中进行赋值(太容易产生错误)。

标签: python loops while-loop


【解决方案1】:

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

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

这等价于:

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

来自iter() 的文档:

如果给定第二个参数 sentinel,则 o 必须是可调用的 目的。在这种情况下创建的迭代器将调用 o 每次调用其next() 方法的参数;如果返回的值是 等于哨兵,StopIteration 将被提升,否则价值 将被退回。

【讨论】:

  • 酷!看起来这正是我正在寻找的。谢谢!
【解决方案2】:

使用返回该值的生成器。

for myVal in myFunc():
 print myVal

这是与yield语句的组合。

【讨论】:

  • 为什么不是 gen-exp? for myVal in (myFunc() for _ in itertools.count()):
猜你喜欢
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
  • 2018-10-25
  • 2020-11-14
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多