Python filter() 函数

4
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参数是非序列类型的情况以及生成什么样的结果呢?


xrange(),生成器等。 - Ashwini Chaudhary
3个回答

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]

1
并非完全如此。filter(lambda x: x%2, {1,2,3,4,5})返回一个list,因为集合不是序列。字典同理。 - roippi
@roippi,我之前不知道这个,非常感谢你。我已经更新了答案。 - anon582847382
2
对于Python3,它已经发生了改变。 - shaik moeed

5

对于 Python 3,这个函数的定义已经发生了变化。

来自 文档

filter(function, iterable)

构造一个迭代器,其中包含 function 返回 true 的 iterable 元素。iterable 可以是序列、支持迭代的容器或迭代器。如果 function 是 None,则假设为恒等函数即删除 iterable 中所有为 false 的元素。

示例:

>>> 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]

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))

结果总是可迭代的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接