您的位置:首页 > 编程语言 > Python开发

python批量执行 map reduce

2015-10-28 09:07 477 查看
# -*- 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 == 1

print 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 0

print sorted([1,5,3,9,7],reverse)
# [9, 7, 5, 3, 1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python