问题:
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/列表理解与lambda-过滤器参考二: https://oldbug.net/q/Cdw1/list-comprehension-vs-lambda-filter
来源:oschina
链接:https://my.oschina.net/u/4432649/blog/4327310