[英]Is a function in a for loop called multiple times?
I want to know if this loop call multiple times "hello".upper() (or any other method/function) while iterating: 我想知道此循环是否在迭代时多次调用“ hello” .upper()(或任何其他方法/函数):
for i in "hello".upper():
#DO SOMETHING
Considering that "hello" doesn't change in the loop, would this be better performance wise?: 考虑到“ hello”在循环中没有变化,这在性能上会更好吗?:
string = "hello".upper()
for i in string:
#DO SOMETHING
The loop target is evaluated only once, after which an iterator is obtained. 循环目标仅评估一次,然后获得迭代器。 Then, next()
on that iterator is called for every iteration of the loop. 然后,循环的每次迭代都将调用该迭代器上的next()
。
You can think of for a in b
as: 您可以将for a in b
视为:
_iter = iter(b) # Evaluates b only ONCE
while True:
try:
a = next(_iter)
except StopIteration:
break
# loop body ...
The argument to the for statement is evaluated once. for语句的参数评估一次。 So it won't be executed multiple times. 因此不会多次执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.