Python高階函式使用
map的使用:map(function, iterable, ...)
map()函式接收兩個引數,一個是函式,一個是Iterable,map將傳入的函式依次作用到序列的每個元素,並把結果作為新的Iterator返回。
>>> def f(x): ...return x + x ... >>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> list(r) [2, 4, 6, 8, 10, 12, 14, 16, 18] # 提供了兩個列表,對相同位置的列表資料進行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19]
reduce的使用:reduce(function, iterable[, initializer])
reduce把一個函式作用在一個序列[x1, x2, x3, ...]上,這個函式必須接收兩個引數,reduce把結果繼續和序列的下一個元素做累積計算。
>>> from functools import reduce >>> def add(x, y): ...return x + y ... >>> reduce(add, [1, 3, 5, 7, 9]) 25 >>> reduce(lambda x, y: x+y, [1,2,3,4,5])# 使用 lambda 匿名函式 15
from functools import reduce def add(x,y): return x + y print (reduce(add, range(1, 101)))
filter的使用:filter(function, iterable)
filter()也接收一個函式和一個序列。和map()不同的是,filter()把傳入的函式依次作用於每個元素,然後根據返回值是True還是False決定保留還是丟棄該元素。
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 結果: [1, 5, 9, 15] def not_empty(s): return s and s.strip() list(filter(not_empty, ['A', '', 'B', None, 'C', ''])) # 結果: ['A', 'B', 'C']
- filter()函式返回的是一個Iterator,也就是一個惰性序列,所以要強迫filter()完成計算結果,需要用list()函式獲得所有結果並返回list。
sorted的使用:sorted(iterable[, cmp[, key[, reverse]]])
- Python內建的sorted()函式就可以對list進行排序:
>>>a = [5,7,6,3,4,1,2] >>> b = sorted(a)# 保留原列表 >>> a [5, 7, 6, 3, 4, 1, 2] >>> b [1, 2, 3, 4, 5, 6, 7]
- 此外,sorted()函式也是一個高階函式,它還可以接收一個key函式來實現自定義的排序,例如按絕對值大小排序:
>>> sorted([36, 5, -12, 9, -21], key=abs) #key指定的函式將作用於list的每一個元素上,並根據key函式返回的結果進行排序。對比原始的list和經過key=abs處理過的list: #list = [36, 5, -12, 9, -21] #keys = [36, 5,12, 9,21] [5, 9, -12, -21, 36] #字串排序 >>> sorted(['bob', 'about', 'Zoo', 'Credit']) ['Credit', 'Zoo', 'about', 'bob']
預設情況下,對字串排序,是按照ASCII的大小比較的,由於'Z' < 'a',結果,大寫字母Z會排在小寫字母a的前面。
- 要進行反向排序,不必改動key函式,可以傳入第三個引數reverse=True:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) ['Zoo', 'Credit', 'bob', 'about']
raw_input的使用:raw_input([prompt])
- prompt: 可選,字串,可作為一個提示語。
- raw_input() 將所有輸入作為字串看待
>>>a = raw_input("input:") input:123 >>> type(a) <type 'str'># 字串 >>> a = raw_input("input:") input:runoob >>> type(a) <type 'str'># 字串 >>>
- input() 需要輸入 python 表示式
>>>a = input("input:") input:123# 輸入整數 >>> type(a) <type 'int'># 整型 >>> a = input("input:") input:"runoob"# 正確,字串表示式 >>> type(a) <type 'str'># 字串 >>> a = input("input:") input:runoob# 報錯,不是表示式 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'runoob' is not defined <type 'str'>