python內建函式(二)之filter,map,sorted
filter
filter()函式接收一個函式 f 和一個iterable的物件,這個函式 f 的作用是對每個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件(False)的元素,返回由符合條件元素組成的新可迭代filter物件。
def is_odd(x): return x % 2 == 1 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', ' ')。
map
map函式應用於每一個可迭代的項,返回的是一個結果map可迭代物件。如果有其他的可迭代引數傳進來,map函式則會把每一個引數都以相應的處理函式進行迭代處理。map()函式接收兩個引數,一個是函式,一個是可迭代物件,map將傳入的函式依次作用到序列的每個元素,並把結果作為新的map可迭代物件<map at 0x13322f34cf8>返回。
有一個list, L = [1,2,3,4,5,6,7,8],我們要將f(x)=x^2作用於這個list上,那麼我們可以使用map函式處理。
def is_odd(x): return x % 2 == 1 def square(x): return x**2 list(map(is_odd, [1, 4, 6, 7, 9, 12, 17])) list(map(square, [1, 4, 6, 7, 9, 12, 17]))
結果:
[True, False, False, True, True, False, True]
[1, 16, 36, 49, 81, 144, 289]
sorted
對List、Dict進行排序,Python提供了兩個方法對給定的List L進行排序:
方法1.用List的成員函式sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函式sorted進行排序(從2.4開始),返回副本,原始輸入不變
l = [1,3,5,-2,-4,-6] l1= sorted(l) l2 = sorted(l,key=abs) print(l1) print(l2)
結果:
[-6, -4, -2, 1, 3, 5]
[1, -2, 3, -4, 5, -6]
l = [[1,2],[3,4,5,6],(7,),'123'] print(sorted(l,key=len))
結果:[(7,), [1, 2], '123', [3, 4, 5, 6]]