[英]Is a function in a for loop declaration will be called for many times in Python?
There is a function and a for loop: 有一个函数和一个for循环:
def helper():
return [1,2,3]
for i in helper():
print(i)
I am wondering if the helper function would only be called once at the initialization of the for loop. 我想知道辅助函数是否只会在for循环的初始化中被调用一次。 As I am thinking that if I call the function and assign the return array to a variable in advance, which would be used in the for loop like this: 正如我在想的那样,如果我调用该函数并预先将return数组分配给一个变量,该变量将在for循环中使用,如下所示:
def helper():
return [1,2,3]
temp = helper()
for i in temp:
print(i)
Is that with less time complexity? 时间复杂度更低吗?
Thanks! 谢谢!
use the yield operation: 使用yield操作:
def helper():
for i in [1,2,3]:
yield i
for i in helper():
print(i)
in this case the helper()
method would return the i
value during each iteration to the calling for
loop. 在这种情况下, helper()
方法将返回i
每次迭代到调用过程值for
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.