[英]Is a function in a for loop declaration will be called for many times in Python?
[英]Is a function in a for loop called multiple times?
我想知道此循环是否在迭代时多次调用“ hello” .upper()(或任何其他方法/函数):
for i in "hello".upper():
#DO SOMETHING
考虑到“ hello”在循环中没有变化,这在性能上会更好吗?:
string = "hello".upper()
for i in string:
#DO SOMETHING
循环目标仅评估一次,然后获得迭代器。 然后,循环的每次迭代都将调用该迭代器上的next()
。
您可以将for a in b
视为:
_iter = iter(b) # Evaluates b only ONCE
while True:
try:
a = next(_iter)
except StopIteration:
break
# loop body ...
for语句的参数评估一次。 因此不会多次执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.