简体   繁体   English

Python过滤器()函数

[英]Python filter() function

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.* 

I came across the above description as part of the definition for the filter(func, a_sequence) function in Python.我在 Python 中作为filter(func, a_sequence)函数定义的一部分遇到了上述描述。

I understand how filter works on a sequence type (lists, strings, tuples).我了解filter如何处理序列类型(列表、字符串、元组)。 However, can you give me situations where a non-sequence type is the an_iter parameter and what kind of result would form?但是,您能告诉我非序列类型是an_iter参数的情况以及会形成什么样的结果吗?

When it says 'non-sequence' , it basically means generators or unordered iterables.当它说'non-sequence' 时,它基本上意味着生成器或无序迭代。 Here is an example with xrange :这是一个带有xrange的示例:

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

And with a set:并带有一组:

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

For python 3, the definition is changed.对于python 3,定义已更改。

From doc来自文档

filter(function, iterable)过滤器(函数,可迭代)

Construct an iterator from those elements of iterable for which function returns true.从那些函数返回 true 的 iterable 元素构造一个迭代器。 iterable may be either a sequence, a container which supports iteration, or an iterator. iterable 可以是一个序列、一个支持迭代的容器或一个迭代器。 If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.如果 function 为 None,则假定恒等函数,即删除所有为 false 的 iterable 元素。

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM