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]
新聞熱點
疑難解答