Python中filter與lambda的結(jié)合使用詳解
filter是Python的內(nèi)置方法。
官方定義是:
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.
第一個參數(shù)為None的情形:
filter(None, '101') # '101' filter(None, [True,False]) #[True] filter(None, [True, 0, 1, -1]) #[True, 1, -1] filter(None, (True, 1, 0, -1, False)) #(True, 1, -1)
第一個參數(shù)為function的情形,如果function(item)為True,則滿足過濾條件。此時的lambda函數(shù)的形式是: lambda x: expression(x)。
注意到,:左邊只能有一個元素x,:右邊為一個關(guān)于x的表達式,且這個表達式的值要么是True, 要么是False.
filter(lambda x: x, [-1, 0, 1]) #[-1, 1] filter(lambda x: not x, [-1, 0, 1]) #[0] def f(x): return True if x == 1 else False filter(lambda x: f(x), [-1, 0, 1]) #[1]
以上這篇Python中filter與lambda的結(jié)合使用詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 詳解python中的lambda與sorted函數(shù)
- Python使用lambda拋出異常實現(xiàn)方法解析
- Python lambda表達式原理及用法解析
- python zip,lambda,map函數(shù)代碼實例
- python匿名函數(shù)lambda原理及實例解析
- python lambda函數(shù)及三個常用的高階函數(shù)
- Python函數(shù)的返回值、匿名函數(shù)lambda、filter函數(shù)、map函數(shù)、reduce函數(shù)用法實例分析
- Python Lambda函數(shù)使用總結(jié)詳解
- Python三元運算與lambda表達式實例解析
- python lambda表達式(匿名函數(shù))寫法解析
- python lambda的使用詳解
相關(guān)文章
python+selenium+chromedriver實現(xiàn)爬蟲示例代碼
這篇文章主要介紹了python+selenium+chromedriver實現(xiàn)爬蟲示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04

python 在指定范圍內(nèi)隨機生成不重復的n個數(shù)實例

python 創(chuàng)建一個空dataframe 然后添加行數(shù)據(jù)的實例

python調(diào)用c++ ctype list傳數(shù)組或者返回數(shù)組的方法

python可擴展的Blender 3D插件開發(fā)匯總