python filter, map, 和reduce

filter(function, sequence):對sequence中的item依次執行function(item),將執行結果爲True的item組成一個List/String/Tuple(取決於sequence的類型)返回:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def f(x): return x != 'a'
>>> filter(f, "abcdef")
'bcdef'

map(function, sequence) :對sequence中的item依次執行function(item),見執行結果組成一個List返回:
>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x) : return x + x
...
>>> map(cube , "abcde")
['aa', 'bb', 'cc', 'dd', 'ee']
另外map也支持多個sequence,這就要求function也支持相應數量的參數輸入:
>>> def add(x, y): return x+y
>>> map(add, range(8), range(8))
[0, 2, 4, 6, 8, 10, 12, 14]

reduce(function, sequence, starting_value):對sequence中的item順序迭代調用function,如果有starting_value,還可以作爲初始值調用,例如可以用來對List求和:
>>> def add(x,y): return x + y
>>> reduce(add, range(1, 11))
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20)
75 (注:1+2+3+4+5+6+7+8+9+10+20)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章