filter、map、sorted和reduce函數
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‘ >>> a.strip() ‘123‘
練習:
請利用filter()過濾出1~100中平方根是整數的數,即結果應該是:
import math def is_sqr(x): return math.sqrt(x) % 1 == 0 print(list(filter(is_sqr, range(1, 101))))
#
def is_sqr(x):
return x**0.5 % 1 == 0
print(list(filter(is_sqr, range(1, 101))))
結果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
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, 5, 6, 7, 8] def pow2(x): return x*x print(list(map(pow2, L))) Output: [1, 4, 9, 16, 25, 36, 49, 64]
sorted
對List、Dict進行排序,Python提供了兩個方法
對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變
sorted(iterable, key=None, reverse=False)
參數說明:
iterable:是可叠代類型;
key:傳入一個函數名,函數的參數是可叠代類型中的每一項,根據函數的返回值大小排序;
reverse:排序規則. reverse = True 降序 或者 reverse = False 升序,有默認值。
返回值:有序列表
# 列表按照其中每一個值的絕對值排序 l1 = [1,3,5,-2,-4,-6] l2 = sorted(l1,key=abs) print(l1) print(l2) #列表按照每一個元素的len排序 l = [[1,2],[3,4,5,6],(7,),‘123‘] print(sorted(l,key=len))
reduce
reduce() 函數會對參數序列中元素進行累積。
函數將一個數據集合(鏈表,元組等)中的所有數據進行下列操作:用傳給 reduce 中的函數 function(有兩個參數)先對集合中的第 1、2 個元素進行操作,得到的結果再與第三個數據用 function 函數運算,最後得到一個結果。
reduce(function, iterable[, initializer])
參數
- function -- 函數,有兩個參數
- iterable -- 可叠代對象
- initializer -- 可選,初始參數
from functools import reduce def add(x,y): return x + y print (reduce(add, range(1, 101)))
Output:
5050
filter、map、sorted和reduce函數