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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法