我有一个列表,我想通过项目的属性进行筛选。

以下哪个是首选(可读性,性能,其他原因)?

xs = [x for x in xs if x.attribute == value]
xs = filter(lambda x: x.attribute == value, xs)

当前回答

我会得出结论:使用列表理解而不是过滤器,因为它

更具可读性 更多的神谕的 更快(对于Python 3.11,参见附带的基准测试,也参见)

请记住,filter返回一个迭代器,而不是一个列表。

python3 -m timeit '[x for x in range(10000000) if x % 2 == 0]'            

1个循环,5个最佳:每循环270毫秒

python3 -m timeit 'list(filter(lambda x: x % 2 == 0, range(10000000)))'

1个循环,最好的5:432毫秒每循环

其他回答

我会得出结论:使用列表理解而不是过滤器,因为它

更具可读性 更多的神谕的 更快(对于Python 3.11,参见附带的基准测试,也参见)

请记住,filter返回一个迭代器,而不是一个列表。

python3 -m timeit '[x for x in range(10000000) if x % 2 == 0]'            

1个循环,5个最佳:每循环270毫秒

python3 -m timeit 'list(filter(lambda x: x % 2 == 0, range(10000000)))'

1个循环,最好的5:432毫秒每循环

当我需要在列表理解之后过滤一些东西时,我使用了一小段。只是过滤器、lambda和列表的组合(或者称为猫的忠诚度和狗的清洁度)。

在这种情况下,我正在读取一个文件,剥离空行,注释掉行,以及在一行的注释之后的任何内容:

# Throw out blank lines and comments
with open('file.txt', 'r') as lines:        
    # From the inside out:
    #    [s.partition('#')[0].strip() for s in lines]... Throws out comments
    #   filter(lambda x: x!= '', [s.part... Filters out blank lines
    #  y for y in filter... Converts filter object to list
    file_contents = [y for y in filter(lambda x: x != '', [s.partition('#')[0].strip() for s in lines])]

一般过滤器稍快,如果使用内置函数。

在您的情况下,我希望列表理解稍微快一些

我觉得第二种方法更容易读懂。它确切地告诉你目的是什么:过滤列表。 注意:不要使用list作为变量名

尽管过滤器可能是“更快的方式”,但“Python方式”是不关心这些事情,除非性能绝对关键(在这种情况下,您不会使用Python!)。