Python filter() 函数

4 投票
3 回答
5041 浏览
提问于 2025-04-18 06:41
filter(function,  an_iter)
*If the iterable an_iter is a sequence, then the returned value is of that same type, 
otherwise the returned value is a list.* 

我在Python的filter(func, a_sequence)函数的定义中看到了上面的描述。

我明白filter是如何在序列类型(比如列表、字符串、元组)上工作的。不过,你能给我一些例子吗?比如在什么情况下an_iter参数不是序列类型,它会产生什么样的结果?

3 个回答

0

看看这个 filter 的有效实现可能会对你有帮助:

def filtered(function, iterable):
    if function is None:
        return (item for item in iterable if item)
    return (item for item in iterable if function(item))

还有一种实现方式(结果是一样的)是:

def filtered(function, iterable):
    if function is None:
        function = bool
    return (item for item in iterable if function(item))

结果总是可以被遍历的。

5

对于Python 3,定义有所变化。

来自 文档

filter(函数, 可迭代对象)

这个函数会根据给定的函数,从可迭代对象中筛选出那些返回真值的元素。可迭代对象可以是一个序列、一个支持迭代的容器,或者一个迭代器。如果函数是None,那么就会默认使用身份函数,也就是说,所有在可迭代对象中返回假值的元素都会被移除。

示例:

>>> filter(lambda x: x in 'hello buddy!', 'hello world')
<filter object at 0x000002ACBEEDCB00> # filter returns object !important

>>> ''.join([i for i in filter(lambda x: x in 'hello buddy!', 'hello world')])
'hello old'

>>> [i for i in filter(lambda n: n % 2, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})]
[1, 3, 5, 7, 9]
5

当提到'非序列'时,实际上是指生成器或无序的可迭代对象。这里有一个使用xrange的例子:

>>> filter(lambda n: n % 2, xrange(10))
[1, 3, 5, 7, 9]

还有一个使用集合的例子:

>>> filter(lambda n: n % 2, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
[1, 3, 5, 7, 9]

撰写回答