python 內置函數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:自定義或匿名函數中所得值是布爾值,true將保留函數所取到的值,false則取反。
??? iterator:可迭代對象。
例:
???? 過濾列表['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
???? 只要含有text字符串及將其取出 or 取反。
s.rfind'text'+1
???? Python3中 rfind() 返回字符串最后一次出現的位置,如果沒有匹配項則返回-1。
???? 數字中0是false,0以上的整數都是true,所以s.rfind'text'后會有+1,沒找到字符及-1+1=0.
# Filter
li = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test'] # 默認保留函數所取到的值 print(list(filter(lambda s: s.rfind('text') + 1, li))) # 取反,下三個例子是一樣的 print(list(filter(lambda s: not s.rfind('text') + 1, li)))
# Noe 自定義函數
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 自定義高階函數
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 匿名函數
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))
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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