Python中filter與lambda的結合使用詳解
阿新 • • 發佈:2020-01-09
filter是Python的內建方法。
官方定義是:
filter(function or None,sequence) -> list,tuple,or string Return those items of sequence for which function(item) is true. If function is None,return the items that are true. If sequence is a tuple or string,return the same type,else return a list.
第一個引數為None的情形:
filter(None,'101') # '101' filter(None,[True,False]) #[True] filter(None,1,-1]) #[True,-1] filter(None,(True,-1,False)) #(True,-1)
第一個引數為function的情形,如果function(item)為True,則滿足過濾條件。此時的lambda函式的形式是: lambda x: expression(x)。
注意到,:左邊只能有一個元素x,:右邊為一個關於x的表示式,且這個表示式的值要麼是True,要麼是False.
filter(lambda x: x,[-1,1]) #[-1,1] filter(lambda x: not x,1]) #[0] def f(x): return True if x == 1 else False filter(lambda x: f(x),1]) #[1]
以上這篇Python中filter與lambda的結合使用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。