python批量执行 map reduce

来源:互联网 发布:单机游戏下载软件 编辑:程序博客网 时间:2024/06/07 08:17


# -*- coding:UTF-8 -*-def f(x):    return x*x # map是python提供的函数,可以把列表中的每个元素执行指定操作,并把结果放在列表中返回# map接收的函数只能接收一个参数print map(f, [1,2,3,4,])# [1, 4, 9, 16]def char2num(s):    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]# 字符串也是一个序列,可以依次对每个字符执行指定操作print map(f, map(char2num, '2468')) # [4, 16, 36, 64]print map(str, [1,2,3,'abc',7,8,9])# ['1', '2', '3', 'abc', '7', '8', '9']##########################################def add(x,y):    return x+y # reduce 是python提供的函数,把列表中相邻两个执行指定操作后作为结果再和下一个进行相同操作# reduce接收的函数只能接收两个参数print reduce(add, [1,2,3,4,5])# 15################################# filter是python提供的函数,根据序列中执行的真假确定是否保留元素,Ture则保留,否则丢弃def is_odd(n):    return n % 2 == 1print filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])# [1, 5, 9, 15]# 去除空字符串def not_empty(s):    return s and s.strip()print filter(not_empty, ['A', '', 'B', None, 'C', '  ','  a bc '])############################ sorted是python提供的函数,可以接收一个列表和一个函数对列表进行排序后返回print sorted([1,5,3,9,7])# [1, 3, 5, 7, 9]def reverse(x,y):    if x>y:        return -1    if x<y:        return 1    return 0print sorted([1,5,3,9,7],reverse)# [9, 7, 5, 3, 1]    




0 0
原创粉丝点击