码迷,mamicode.com
首页 > 其他好文 > 详细

map 和 reduce

时间:2016-10-01 22:12:05      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

注意:reduce需要 from functools import reduce

map的使用:

>>> def func(x):
...     return x*x
...
>>> [x for x in range(1,11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> l=[x for x in range(1,11)]
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(map(func,l))
<map object at 0x014E94F0>
>>> ll=list(map(func,l))                #重点用法
>>> ll
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

reduce用法:

>>> l=[i for i in range(1,6)]
>>> l
[1, 2, 3, 4, 5]
>>> def func(x,y):
...     return(x*10+y)
...

>>> reduce(func,l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name reduce is not defined
                                                             #单个数乘10,组成一个整数
>>> from functools import reduce              #重点 
>>> reduce(func,l)                                     #重点 
12345

>>> ll=reduce(func,l)
>>> type(ll)
<class int>                                            

 

 

 

dd

 

map 和 reduce

标签:

原文地址:http://www.cnblogs.com/hanggegege/p/5926333.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!