python中filter()函數

filter()函數是 Python 內置的另外一個有用的高階函數,filter()函數接收一個函數 f 和一個list,這個函數 f 的做用是對每一個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。函數

例如,要從一個list [1, 4, 6, 7, 9, 12, 17]中刪除偶數,保留奇數,首先,要編寫一個判斷奇數的函數:spa

def is_odd(x):
    return x % 2 == 1

而後,利用filter()過濾掉偶數:code

>>>filter(is_odd, [1, 4, 6, 7, 9, 12, 17])

結果:blog

[1, 7, 9, 17]

利用filter(),能夠完成不少有用的功能,例如,刪除 None 或者空字符串:ip

def is_not_empty(s):
    return s and len(s.strip()) > 0
>>>filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])

結果:字符串

['test', 'str', 'END']

注意: s.strip(rm) 刪除 s 字符串中開頭、結尾處的 rm 序列的字符。class

當rm爲空時,默認刪除空白符(包括'\n', '\r', '\t', ' '),以下:test

>>> a = ' 123'
>>> a.strip()
'123'import

>>> a = '\t\t123\r\n'
>>> a.strip()
'123'方法

練習:

請利用filter()過濾出1~100中平方根是整數的數,即結果應該是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

方法:

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
print filter(is_sqr, range(1, 101))

結果:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
相關文章
相關標籤/搜索