Python filter過濾器原理及實例應(yīng)用
filter的語法:filter(函數(shù)名字,可迭代的變量)
其實filter就是一個“過濾器”:把【可迭代的變量】中的值,挨個地傳給函數(shù)進行處理,那些使得函數(shù)的返回值為True的變量組成的迭代器對象就是filter表達式的結(jié)果
那filter的第一個參數(shù),即函數(shù)的返回的值必須是bool類型,第二個參數(shù)必須是可迭代的變量:字符串、字典、元組、集合
其實從源碼中也能大概看出filter是個什么東西
下面來看一些實際的代碼示例:
打印列表中以“A”開頭的名字
def first_name(x): if x.startswith('A'): return True else: return Falsename = ['Alex','Hana','Anny','Sunny']f = filter(first_name, name)a_name = list(f)print('f:',f)print('a_name:',a_name)
輸出結(jié)果為:
f: <filter object at 0x10cb28700>a_name: [’Alex’, ’Anny’]
下面再來一個filter和lambda結(jié)合的例子:
打印人員信息的字典中,年紀(jì)大于18的人
people = [ {'name':'Alex','age':20}, {'name':'Hana','age':19}, {'name':'Anny','age':16}, {'name':'Sunny','age':18},]f = filter(lambda p:p['age']>18, people)print(list(f))
輸出結(jié)果為:
[{’name’: ’Alex’, ’age’: 20}, {’name’: ’Hana’, ’age’: 19}]
第二個參數(shù)也可以是字符串:
qq_mail = '[email protected]'f = filter(lambda m:m.isnumeric(),qq_mail)print(list(f))
輸出結(jié)果:
[’1’, ’2’, ’3’]
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Django視圖類型總結(jié)2. Xml簡介_動力節(jié)點Java學(xué)院整理3. Intellij IDEA 關(guān)閉和開啟自動更新的提示?4. Ajax引擎 ajax請求步驟詳細代碼5. 解析原生JS getComputedStyle6. idea設(shè)置自動導(dǎo)入依賴的方法步驟7. IntelliJ IDEA Java項目手動添加依賴 jar 包的方法(圖解)8. idea重置默認(rèn)配置的方法步驟9. intellij idea設(shè)置統(tǒng)一JavaDoc模板的方法詳解10. Spring @Profile注解實現(xiàn)多環(huán)境配置
