python 內(nèi)置函數(shù)filter
class filter(object): """ filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. """
filter(func,iterator)
??? func:自定義或匿名函數(shù)中所得值是布爾值,true將保留函數(shù)所取到的值,false則取反。
??? iterator:可迭代對(duì)象。
例:
???? 過濾列表['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
???? 只要含有text字符串及將其取出 or 取反。
s.rfind'text'+1
???? Python3中 rfind() 返回字符串最后一次出現(xiàn)的位置,如果沒有匹配項(xiàng)則返回-1。
???? 數(shù)字中0是false,0以上的整數(shù)都是true,所以s.rfind'text'后會(huì)有+1,沒找到字符及-1+1=0.
# Filter
li = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test'] # 默認(rèn)保留函數(shù)所取到的值 print(list(filter(lambda s: s.rfind('text') + 1, li))) # 取反,下三個(gè)例子是一樣的 print(list(filter(lambda s: not s.rfind('text') + 1, li)))
# Noe 自定義函數(shù)
l1 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test'] def distinguish(l): nl = [] for s in l: if s.rfind("text") + 1: nl.append(s) return nl print(distinguish(l1))
# Two 自定義高階函數(shù)
l2 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test'] def f(s): return s.rfind('text') + 1 def distinguish(func, array): nl = [] for s in array: if func(s): nl.append(s) return nl print(distinguish(f, l2))
# Three 匿名函數(shù)
l3 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test'] def distinguish(func, array): nl = [] for s in array: if func(s): nl.append(s) return nl print(distinguish(lambda s: s.rfind('text') + 1, l3))
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
