国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > 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]            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 前郭尔| 咸丰县| 莎车县| 天水市| 巫山县| 巴东县| 姜堰市| 洮南市| 同德县| 东宁县| 平邑县| 郑州市| 英山县| 曲松县| 历史| 甘谷县| 乌兰县| 西贡区| 信丰县| 寿光市| 交口县| 霍州市| 临澧县| 琼中| 长岭县| 宁国市| 荥阳市| 滕州市| 正阳县| 盐源县| 项城市| 咸丰县| 龙井市| 米林县| 武宁县| 鄂伦春自治旗| 特克斯县| 凤山县| 仁怀市| 旺苍县| 信丰县|