map()
map()函數(shù)的作用主要是根據(jù)函數(shù)的要求對(duì)序列做映射
- function:是一個(gè)函數(shù)
- sequence:是一個(gè)或多個(gè)序列,取決于function需要幾個(gè)參數(shù)
- 返回值是一個(gè)list
In [1]: func = lambda x:x**2
In [2]: map(func,[i for i in range(10)])
Out[2]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce()
reduce()函數(shù)的作用是會(huì)根據(jù)序列中的值進(jìn)行累計(jì)
- function:該函數(shù)有兩個(gè)參數(shù)
- sequence:序列可以是str疙赠,tuple唤衫,list
- initial:固定初始值
In [1]: func = lambda x,y:x*10 + y
In [2]: reduce(func,[1,3,5,7,9])
Out[2]: 13579
在Python3里,reduce函數(shù)已經(jīng)被從全局名字空間里移除了, 它現(xiàn)在被放置在fucntools模塊里用的話要先引入:
from functools import reduce
filter()
filter()函數(shù)的作用主要是對(duì)序列做過濾
- function:接受一個(gè)參數(shù)询筏,返回布爾值True或False
- sequence:序列可以是str滋尉,tuple,list
In [2]: filter(lambda x:x%2,[i for i in range(10)])
Out[2]: [1, 3, 5, 7, 9]
sorted()
sorted()函數(shù)的作用主要是針對(duì)序列做排序
用法:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
In [1]: sorted([3,4,5,1,2,9,0])
Out[1]: [0, 1, 2, 3, 4, 5, 9]
In [2]: sorted([3,4,5,1,2,9,0],reverse=-1)
Out[2]: [9, 5, 4, 3, 2, 1, 0]