列表理解與 lambda + 過濾器 - List comprehension vs. lambda + filter

問題:

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.我碰巧發現自己有一個基本的過濾需求:我有一個列表,我必須按項目的屬性對其進行過濾。

My code looked like this:我的代碼如下所示:

my_list = [x for x in my_list if x.attribute == value]

But then I thought, wouldn't it be better to write it like this?但後來我想,這樣寫不是更好嗎?

my_list = filter(lambda x: x.attribute == value, my_list)

It's more readable, and if needed for performance the lambda could be taken out to gain something.它更具可讀性,如果需要性能,可以取出 lambda 以獲得一些東西。

Question is: are there any caveats in using the second way?問題是:使用第二種方式有什麼注意事項嗎? Any performance difference?有什麼性能差異嗎? Am I missing the Pythonic Way™ entirely and should do it in yet another way (such as using itemgetter instead of the lambda)?我是否完全錯過了 Pythonic Way™,應該以另一種方式來實現(例如使用 itemgetter 而不是 lambda)?


解決方案:

參考一: https://stackoom.com/question/Cdw1
參考二: List comprehension vs. lambda + filter
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章