python 內建函數filter,python函數filter

來源:互聯網
上載者:User

python 內建函數filter,python函數filter

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 nlprint(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') + 1def distinguish(func, array): nl = [] for s in array:  if func(s):   nl.append(s) return nlprint(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 nlprint(distinguish(lambda s: s.rfind('text') + 1, l3))

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.