python reduce map_python里的map和reduce

有不少文章介绍python的map与reduce,这到底是什么样的东西呢?

先看看google的paper里对mapreduce的解释

MapReduce is a programming model and an associated

implementation for processing and generating large

data sets. Users specify a map function that processes a

key/value pair to generate a set of intermediate key/value

pairs, and a reduce function that merges all intermediate

values associated with the same intermediate key.

map

map(function, iterable, ...)的第一个参数是一个函数,第二个参数接受一个iterable对象(字符串,列表,元组等)。该函数返回一个列表。

python实现map的代码

实现:将输入的不规范的用户名转换成首字母大写的标准格式

逻辑写的简单点,就3种情况,当然可以写成4种,就相对复杂了。。。初次循环,首字母小写

非初次循环,字母大写

其它(因为初次循环,首字母大写和非初次循环,字母小写默认就满足我们的需求)def lower2upper(s):

loop = 0   '''循环计数'''

str = ""    '''定义一个空字符串'''

for i in s:

if i.islower() and loop ==0:

str = str + i.upper()

loop +=1

elif i.isupper() and loop !=0:

str = str + i.lower()

loop +=1

else:

str = str + i

loop +=1

return str

result = map(lower2upper,["adam","LiSA","ChEn","Peter","tOM"])

print result

reducereduce(function, iterable[, initializer])把函数从左到右累积作用在元素上,产生一个数值。如reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])就是计算((((1+2)+3)+4)+5)。Python提供的sum()函数可以接受一个list并求和,现实现一个prod()函数,可以接受一个list并利用reduce()求积。def prod(list):def multiply(x, y):return x * yreturn reduce(multiply, list)print prod([1, 3, 5, 7])map和reduce我们可以综合利用map和reduce来完成一个简单的字符串到数字的程序。def str2int(s):def fn(x, y):return x * 10 + ydef char2num(s):return {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}return reduce(fn, map(char2num, s))print str2int("12345")其中map用于将字符串拆分为对应的数字,并以list的方式返回。reduce用来累加各个位上的和。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值