首頁  >  文章  >  後端開發  >  Python中有關filter的用法詳解

Python中有關filter的用法詳解

黄舟
黄舟原創
2017-08-23 13:19:193013瀏覽


Python中有關filter的用法詳解

1 class filter(object)
2  |  filter(function or None, iterable) --> filter object
3  |  
4  |  Return an iterator yielding those items of iterable for which function(item)
5  |  is true. If function is None, return the items that are true.

filter讀入iterable所有的項,判斷這些項對function是否為真,傳回一個包含所有為真的項的迭代器。如果function是None,則傳回非空的項。

1 In [2]: import re
2 In [3]: i = re.split(',',"123,,123213,,,123213,")
3 In [4]: i4 Out[4]: ['123', '', '123213', '', '', '123213', '']

這時,清單i內包含空字串。

1 In [7]: print(*filter(None, i))
2 123 123213 123213

這時filter把列表中的空串過濾掉了,得到一個只含非空串的迭代器。

In [9]: print(list(filter(lambda x:x=='', i)))
['', '', '', '']

由於lambda對空串為真,所以filter把非空串過濾掉,只剩下空字串。

以上是Python中有關filter的用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn