2017-09-15 40 views
0

我有一個返回整數列表的函數。Python:for循環'header'中的函數

def my_function(param: int)->list: 
    do_sth... 
    return list 

在另一個模塊中,我有一個for循環迭代通過該函數的返回列表。 現在我的問題是:

for x in my_function(x): 
    do_sth... 

沒有for循環調用這個函數的每一個迴路或僅一次的開始?

+2

在你的功能(或打印)中添加一個全局計數器,你將得到你的答案。然而,我發現你的電話很奇怪,因爲你在'for x in my_function(x)'中使用x兩次' – Nathan

+4

[for循環評估它的表達式列表多少次?](https://stackoverflow.com/問題/ 24470072 /多少次 - 做一個for-loop-evaluate-its-expression-list) – Sayse

+1

* [「表達式列表被評估一次;它應該產生一個可迭代的對象。「](https://docs.python.org/3/reference/compound_stmts.html#for)* – poke

回答

1

其實答案是隻能調用一次,當你做以下事情:

for x in my_function(x): 
    do_sth... 

創建my_function(X)將首先進行評估,然後返回一個列表,這樣的聲明是這樣的:

for x in [...]: 
    do_sth... 

您可以在創建my_function正文中添加打印功能,您將看到打印函數被調用一次。

1

這確實是this question的重複。然而,爲了更清楚的解釋(信用@Nathan)沒有進入技術術語的緣故,這裏有一個例子:

>>> def a(): 
...  print("a() was called") 
...  return [1, 2, 3, 4, 5] 
... 
>>> for i in a(): 
...  print(i) 
... 
a() was called 
1 
2 
3 
4 
5 

正如你可以在這裏看到,該函數a()僅當for循環調用一次跑。

希望這有助於!