python高階函式(filter與sorted)
阿新 • • 發佈:2020-12-01
filter()
Python內建的filter()
函式用於過濾序列
filter()
接收一個函式和一個序列。
filter()
把傳入的函式依次作用於每個元素,然後根據返回值是True
還是False
決定保留還是丟棄該元素。
# def s(n): #定義函式 # return n%2==0 #函式輸出結果為偶數 # a=list(filter(s,[1,2,3,4,5,6,7,8,9])) #將數列中的數依次加入到函式中篩選數列中為偶數的數 # print(a)
把一個序列中的空字串刪掉,可以這麼寫:
# def not_empty(s): # return s and s.strip()# a=list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) # print(a)
注意:filter()
函式返回的是一個Iterator
,也就是一個惰性序列,所以要強迫filter()
完成計算結果,需要用list()
函式獲得所有結果並返回list
小結
filter()
的作用是從一個序列中篩出符合條件的元素。由於filter()
使用了惰性計算,所以只有在取filter()
結果的時候,才會真正篩選並每次返回下一個篩出的元素。
sorted 排序演算法
Python內建的sorted()
函式就可以對list進行排序
# a=[45,16,2,15,449,5,25,1]# b=sorted(a) # print(b)
反向排序 ,加入引數reverse=True
# a=[45,16,2,15,449,5,25,1] # b=sorted(a,reverse=True) # print(b)
預設情況下,對字串排序,是按照ASCII的大小比較的,由於'Z' < 'a'
,結果,大寫字母Z
會排在小寫字母a的前面
# a=['Z','a','e','T'] # b=sorted(a) # print(b)
用key=str.lower可以忽略大小寫
# a=['Z','a','e','T'] # b=sorted(a,key=str.lower)# print(b)
小結
sorted()
也是一個高階函式。用sorted()
排序的關鍵在於實現一個對映函式。