[英]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.