filter函數一般用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表.也就是列表解析,集合解析,字典解析中提及的過濾元素.
這裡順便說一點題外話,在那篇文章中忘了提及: 列表解析屬於語法糖,編譯器會自動對其優化,但是其簡潔性大大的提高了編程的高效性和可閱讀性.
我們可以先看一下Python3的AP是如何描述的:
filter(function, iterable)
Construct an iterator 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 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 the generator expression (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.
翻譯一下就是如下:
# 構建一個隨機列表 lis = [randint(0,10) for _ in range(10)] print(lis) #輸出為[2, 9, 3, 5, 6, 9, 6, 10, 9, 5] # 使用filter函數進行賽選其中的奇數元素 g = filter(lambda x: x & 1 != 0,lis) print(g) # 輸出為 <filter object at 0x000001551904BA88> # 使用返回的迭代器生成列表 res = list(g) print(res) #輸出為[9, 3, 5, 9, 9, 5]
這裡就使用的是lambda表達式,因為這樣很簡潔,能夠實現大部分需求,不是lambda表達式也可以,如下:
lis = [randint(0,10) for _ in range(10)] print(lis) # [3, 3, 4, 8, 3, 4, 5, 1, 0, 0] # 判斷是否為奇數 def isOdd(x): return x & 1 res = list(filter(isOdd, lis)) print(res) #[3, 3, 3, 5, 1]
這裡我自己定義的函數寫得很簡單,你也可以將其寫得很複雜,
原文:https://www.cnblogs.com/ltozvxe/p/12395948.html