Python 过滤器() 函数

nsa*_*uel 4 python input filter

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.* 
Run Code Online (Sandbox Code Playgroud)

我发现上述描述是filter(func, a_sequence) Python 函数定义的一部分。

我了解filter序列类型(列表、字符串、元组)的工作原理。但是,您能否给我介绍一下以非序列类型为an_iter参数的情况以及会形成什么样的结果?

Ale*_*ton 5

当它说“非序列”时,它基本上意味着生成器或无序迭代。这是一个示例xrange

>>> filter(lambda n: n % 2, xrange(10))
[1, 3, 5, 7, 9]
Run Code Online (Sandbox Code Playgroud)

并且有一套:

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

  • 对于python3,它已经改变了。 (2认同)

sha*_*eed 5

对于 python 3,定义已更改。

来自文档

过滤器(函数,可迭代)

从 iterable 的那些函数返回 true 的元素构造一个迭代器。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]
Run Code Online (Sandbox Code Playgroud)