首页 > 编程 > Python > 正文

对python过滤器和lambda函数的用法详解

2020-02-16 00:47:25
字体:
来源:转载
供稿:网友

1. 过滤器

Python 具有通过列表解析 将列表映射到其它列表的强大能力。这种能力同过滤机制结合使用,使列表中的有些元素被映射的同时跳过另外一些元素。

过滤列表语法: [ mapping-expression for element in source-list if filter-expression ]

这是列表解析的扩展,前三部分都是相同的,最后一部分,以 if开头的是过滤器表达式。过滤器表达式可以是返回值为真或者假的任何表达式 (在 Python 中是几乎任何东西)。任何经过滤器表达式演算值为真的元素都可以包含在映射中,其它的元素都将忽略,它们不会进入映射表达式,更不会包含在输出列表中。

列表过滤介绍

>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]>>> [elem for elem in li if len(elem) > 1]['mpilgrim', 'foo']// 由于 Python 会遍历整个列表,它将对每个元素执行过滤器表达式,如果过滤器表达式演算值为真,该元素就会被映射,同时映射表达式的结果将包含在返回的列表中,这里过滤掉了所有单字符的字符串,留下了一个由长字符串构成的列表。>>> [elem for elem in li if elem != "b"]['a', 'mpilgrim', 'foo', 'c', 'd', 'd']// 这里过滤掉了一个特定值 b ,注意这个过滤器会过滤掉所有的 b, 因为每次取出 b, 过滤表达式都将为假。>>> [elem for elem in li if li.count(elem) == 1]['a', 'mpilgrim', 'foo', 'c']// count 是一个列表方法,返回某个值在列表中出现的次数,你可以认为这个过滤器将从列表中删除重复元素,返回一个只包含了在原始列表中有着唯一值拷贝的列表。但并非如此,因为在原始列表中出现两次的值 (在本例中, b 和 d ) 被完全剔除了,从一个列表中排除重复值有多种方法,但过滤并不是其中的一种。

filter 内置函数

Python2.7.13官方文档中的介绍: filter(function, iterable) Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.

Python内建的filter()函数用于过滤序列

// 保留长度大于1的字符串>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]>>> def func(s):... return len(s) > 1>>> filter(func,li)['mpilgrim', 'foo']// 删除奇数>>> def del_odd(n):... return n % 2 == 0>>> filter(del_odd,[0,1,2,3,4,5,6,7,8,9])[0, 2, 4, 6, 8]            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表