首页 > 代码库 > 内置函数补充map、reduce和filter等

内置函数补充map、reduce和filter等

map函数:映射功能

map(function, iterable, ...):可迭代对象向函数function传入元素,并得到一个返回值.

1 >>> map(lambda x :x+1,[1,2,3.4])
2 [2, 3, 4.4]
3 >>> map(lambda x :x+"_key",{"key":"value","key1":"value2"})
4 [key1_key, key_key]

注意,在python2和python3中,map函数的返回的类型不一样。

python2 map函数返回的是列表。

1 >>> l = map(lambda x :x+"_key",{"key":"value","key1":"value2"})
2 >>> l
3 [key1_key, key_key]
4 >>> type(l)
5 <type list>

python3中,map函数返回的是map对象,它是一个迭代器,可以调用next方法。

 1 >>> l = map(lambda x :x+"_key",{"key":"value","key1":"value2"})
 2 >>> l
 3 <map object at 0x10558c1d0>
 4 >>> next(l)
 5 key_key
 6 >>> 
 7 >>> next(l)
 8 key1_key
 9 >>> next(l)
10 Traceback (most recent call last):
11   File "<stdin>", line 1, in <module>
12 StopIteration

 reduce函数:处理一个序列,并返回一个值,适合求和。python2中自带reduce函数,python3中需要导入“from functool import reduce”。

reduce(function, iterable[, initializer ]):可迭代对象会把元素传给函数function,function会接收到两个值,如果未指定初始值initializer,则默认传0.

python3

1 >>> from functools import reduce 
2 >>> l = reduce(lambda x,y:x+y,range(1,100),100) #给一个初始值100
3 >>> l
4 5050

 

filter函数:

filter(function, iterable):把可迭代对象变成迭代器,把每一个元素传入函数function,function会返回布尔值,结果为Ture则保留。

python2: 

 1 >>> item_price =[
 2 ...     {"item":"apple","price":5},
 3 ...     {"item":"egg","price":4.5},
 4 ...     {"item":"water","price":1.5},
 5 ...     {"item":"fish","price":15}
 6 ... ]
 7 >>> l = filter(lambda d: d["price"]>=5,item_price)
 8 >>> type(l)
 9 <type list>
10 >>> l
11 [{item: apple, price: 5}, {item: fish, price: 15}]

python3

>>> item_price =[
...     {"item":"apple","price":5},
...     {"item":"egg","price":4.5},
...     {"item":"water","price":1.5},
...     {"item":"fish","price":15}
... ]
>>> l = filter(lambda d: d["price"]>=5,item_price)
>>> type(l)
<class filter>
>>> l
<filter object at 0x10558c438>
>>> next(l)
{item: apple, price: 5}
>>> next(l)
{item: fish, price: 15}
>>> next(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 pyhton3中封装了很多,类型就是类。所以我们使用map、reduce和fliter返回的都是各自的类型,且都是生成器,可以调用next方法。而python2则都是列表。

内置函数补充map、reduce和filter等