gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:04:45 25 4
gpt4 key购买 nike

我想做如下的事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com