如果我這樣做,確實split()
被調用每次迭代?:Python中的'in'運算符是「懶」嗎?
a = [word for word in post.split() if len(word) > 10]
我應該這樣做,而不是有更好的表現?
s = post.split()
a = [word for word in s if len(word) > 10]
如果我這樣做,確實split()
被調用每次迭代?:Python中的'in'運算符是「懶」嗎?
a = [word for word in post.split() if len(word) > 10]
我應該這樣做,而不是有更好的表現?
s = post.split()
a = [word for word in s if len(word) > 10]
單個表達式很好 - post.split()
只會被調用一次。
這是因爲迭代通過你的對象的值for
循環在Python支持迭代 - 它不保留檢查,對你可能在另一種語言看到一些條件語句,如通過下一個循環數組
因此,在這種情況下,post.split()
產生您的對象,for
循環然後迭代,不需要再次調用。
「懶」 -ness也是不正確的術語,被詢問這裏,因爲它是指延遲表達式求值,直到它被嚴格需要的做法。這裏我們當然需要需要來撥打post.split()
,問題更多的是「效率」。請參閱Wiki上的Lazy evaluation以獲得對策略的詳細描述。
post.split()
只被調用一次。您可以通過打印,每次當它被調用的函數替換post.split()
驗證:
>>> post = 'a b c d'
>>> def split_post():
... print('split_post is called')
... return post.split()
...
>>> a = [word for word in split_post() if len(word) > 10]
split_post is called
你並不需要表達分成兩個語句的性能。
這不是「懶」的意思。 – vartec
@vartec你想介紹一下更多,還是完全不同的話題? – sooqua
這實際上不是'in'運算符。儘管使用了相同的關鍵字,但它在列表理解中是一個「... ... ... ...」子句,儘管它並不完全相同。 – Blckknght