python中filter()函數

來源:互聯網
上載者:User

標籤:lis   mat   nbsp   blog   函數   als   ret   另一個   empty   

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

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

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

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

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

結果:

[1, 7, 9, 17]

利用filter(),可以完成很多有用的功能,例如,刪除 None 或者Null 字元串:

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 序列的字元。

當rm為空白時,預設刪除空白符(包括‘\n‘, ‘\r‘, ‘\t‘, ‘ ‘),如下:

>>> a = ‘ 123‘
>>> a.strip()
‘123‘

>>> a = ‘\t\t123\r\n‘
>>> a.strip()
‘123‘

練習:

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

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

方法:

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

結果:

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

python中filter()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.