It is strange how much beauty varies for different people.
(奇怪的是,不同的人有多少美丽。)
I find the list comprehension much clearer than filter
+ lambda
, but use whichever you find easier. (我发现列表理解比filter
+ lambda
更清晰,但请使用任何您发现更容易的方法。)
There are two things that may slow down your use of filter
.
(有两件事可能会减慢您使用filter
。)
The first is the function call overhead: as soon as you use a Python function (whether created by def
or lambda
) it is likely that filter will be slower than the list comprehension.
(第一个是函数调用开销:使用Python函数(无论是由def
还是lambda
创建)后,filter的运行速度可能会比list理解的速度慢。)
It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there. (几乎可以肯定,这还不够重要,并且在对代码进行计时并发现它是瓶颈之前,您不应该对性能进行太多的考虑,但是区别仍然存在。)
The other overhead that might apply is that the lambda is being forced to access a scoped variable ( value
).
(可能适用的其他开销是,lambda被强制访问作用域变量( value
)。)
That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. (这比访问局部变量要慢,并且在Python 2.x中,列表推导仅访问局部变量。)
If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing value
through a closure and this difference won't apply. (如果您使用的是Python 3.x,则列表推导是在单独的函数中运行的,因此它也将通过闭包来访问value
,并且这种区别将不适用。)
The other option to consider is to use a generator instead of a list comprehension:
(要考虑的另一个选项是使用生成器而不是列表推导:)
def filterbyvalue(seq, value):
for el in seq:
if el.attribute==value: yield el
Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.
(然后,在您的主要代码(这才是真正的可读性)中,您已经用有希望的有意义的函数名称替换了列表理解和过滤器。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…