簡體   English   中英

for循環聲明中的函數是否會在Python中多次調用?

[英]Is a function in a for loop declaration will be called for many times in Python?

有一個函數和一個for循環:

def helper():
    return [1,2,3]

for i in helper():
    print(i)

我想知道輔助函數是否只會在for循環的初始化中被調用一次。 正如我在想的那樣,如果我調用該函數並預先將return數組分配給一個變量,該變量將在for循環中使用,如下所示:

def helper():
    return [1,2,3]
temp = helper()
for i in temp:
    print(i)

時間復雜度更低嗎?

謝謝!

使用yield操作:

def helper():
    for i in [1,2,3]:
         yield i

for i in helper():
    print(i)

在這種情況下, helper()方法將返回i每次迭代到調用過程值for循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM