内置函數——filter和map
filter
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()過濾掉偶數:
>>>list(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()) > 0
>>>list(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'
練習:
請利用filter()過濾出1~100中平方根是整數的數,即結果應該是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
方法:
import mathdef is_sqr(x):
return math.sqrt(x) % 1 == 0print(list(filter(is_sqr, range(1, 101))))
map
Python中的map函數應用于每一個可疊代的項,傳回的是一個結果list。如果有其他的可疊代參數傳進來,map函數則會把每一個參數都以相應的處理函數進行疊代處理。map()函數接收兩個參數,一個是函數,一個是序列,map将傳入的函數依次作用到序列的每個元素,并把結果作為新的list傳回。
有一個list, L = [1,2,3,4,5,6,7,8],我們要将f(x)=x^2作用于這個list上,那麼我們可以使用map函數處理。
>>> L = [1,2,3,4,]
>>> def pow2(x):
... return x*x
...
>>> list(map(pow2,L))