標籤:hid for 代碼 函數 tool arguments class erro 編程
函數式編程,使代碼簡潔高效。
Map函數:
map(func, *iterables),作用是將一個列表映射到另一個列表。
class map(object): """ map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted. """
View Code
使用方法:
def f(x): return x**2li = range(1,10)res = map(f,li)print(res)print(list(res))"""<map object at 0x000000000117E2E8>[1, 4, 9, 16, 25, 36, 49, 64, 81]"""
map(function, iterable, ...)
map()函數接收兩個參數,一個是函數,一個是可迭代的對象,map將傳入的函數依次作用到序列的每個元素,返回一個map對象,不是list。
基本等價於 [f(x) for x in interable],列表推導比map效率要高一些
map(lambda x: x+1, range(1, 3)) => [x+1 for x in range(1,3)]
str = ["far","foo","bar"]mp = map(lambda x:x.upper(),str)res = list(mp)print(res)"""[‘FAR‘, ‘FOO‘, ‘BAR‘]"""
View Code
Reduce函數
reduce(function, sequence[, initial]),對可迭代對象依次做累計操作,如依次相加或相乘。
reduce()方法接收一個函數作為累加器(accumulator),數組中的每個值(從左至右)開始合并,最終為一個值。
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__ """ reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. """
View Code
直接使用會報錯
reduce(lambda x, y : x + y, [1, 3, 5, 7, 9])
"""
NameError: name ‘reduce‘ is not defined
"""
正確的使用是:reduce是functools中的一個函數,需要引用:from functools import reduce
使用方法:
from functools import reduceres1 = reduce(lambda x, y: x*y, [1, 2, 3])res2 = reduce(lambda x, y : x + y, [1, 3, 5])print(res1)print(res2)"""69"""
Filter函數
filter(function or None, iterable),作用是按照所定義的函數過濾掉列表中的一些元素
class filter(object): """ filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. """
View Code
使用方法:
flt = filter(lambda x: x > 5, range(10))res = list(flt)print(flt)print(res)"""<filter object at 0x0000000000649A58>[6, 7, 8, 9]"""
Python函數式編程 map reduce filter