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
的示例:
>>> 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]
对于python 3,定义改变了。
从医生过滤器(函数,iterable)
从这些元素构造一个迭代器函数返回true的可迭代对象。Iterable可以是aSequence,支持迭代的容器或迭代器。如果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]