python函式每日一講 - filter函式過濾序列

pythontab發表於2018-03-22

描述

filter()函式用於過濾序列, 過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。

filter()函式接收一個函式 func 和一個iterable(可以是list,字串等),這個函式 func 的作用是對每個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件的元素,最後將返回 True 的元素放到新列表中。


語法

filter(function, iterable)


引數

function -- 判斷函式。

iterable -- 可迭代物件。


返回值

返回符合條件的新列表。


適用版本

2.x

3.x


英文解釋

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.


Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.


例項

#!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [1,2,4,6,8,9]
def is_gt_5(num):
    return num > 5
new_list = filter(is_gt_5, list)
print(new_list)


輸出結果

[6, 8, 9]


高階用法

1. 過濾非數字字元

>>> name = 'pythontab.com 2018'
>>> filter(str.isdigit, name)
'2018'

2. 過濾數字

>>> filter(str.isalpha, name)
'pythontabcom'

3. 保留數字和小數點

>>> filter(lambda char: char in ‘0123456789.’, name) 
'.2018'


相關文章