python語法之filter 函式

2021-09-20 06:45:41 字數 1454 閱讀 5221

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 或者空字串:

def

is_not_empty

(s):

return s and

len(s.strip())

>

0filter

(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 math

defis_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函式

例項環境 help filter help on built in function filter in module builtin filter filter function or none,sequence list,tuple,or string return those items of...

Python函式之filter 和strip

python函式之filter 和strip 編寫乙個remove false 函式 將引數中的 假 去掉 remove false 0,1,2,false,fishc 34 1,2,fishc 34 lst 0,1,2,false,fishc 34 def remove false lst ret...

Python語法之With語句

有一些任務,可能事先需要設定,事後做清理工作。對於這種場景,python的with語句提供了一種非常方便的處理方式。乙個很好的例子是檔案處理,你需要獲取乙個檔案控制代碼,從檔案中讀取資料,然後關閉檔案控制代碼。如果不用with語句,如下 file open tmp foo.txt data file...