列表理解与 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章