python-列表推倒式-轻量级循环
2016-03-06 00:51
621 查看
列表推倒式是利用其它列表创建新的列表的方法。
示例
当添加一个if语句到列表推倒式的时候
联合语句时候(男生女生首字母相同的在一起,好厉害O(∩_∩)O~~)
但是这个效率不是很高,他要把男生和女生的名字每个都要匹配一遍,so
示例
>>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
当添加一个if语句到列表推倒式的时候
>>> [x*x for x in range(10) if x%2==0] [0, 4, 16, 36, 64]
联合语句时候(男生女生首字母相同的在一起,好厉害O(∩_∩)O~~)
>>> boys=['amada','bwsf','cdws'] >>> girls=['alice','batterf','cauew'] >>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]] ['amada+alice', 'bwsf+batterf', 'cdws+cauew']
但是这个效率不是很高,他要把男生和女生的名字每个都要匹配一遍,so
boys=['amada','bwsf','cdws'] girls=['alice','batterf','cauew'] letterGirls={} for girl in girls: letterGirls.setdefault(girl[0],[]).append(girl) print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
相关文章推荐
- Python while 循环
- python如何通过protobuf实现rpc
- Python切片知识解析
- 基于Python实现一个简单的银行转账操作
- Python 配置
- Python学习之路--面向对象
- Python学习笔记系列(二):安装第三方软件库(Windows)
- Python使用mechanize模拟登录、抓取数据的代码
- python2.5 编译出错
- 冒泡排序(python版)
- vim+python+OpenCV学习六 : 滤波初级
- 天灵灵,地灵灵,但愿这个一定灵!!!python调用win32api,启动应用程序窗口
- Python Select 解析
- python通过protobuf实现rpc
- Python图像处理库PIL的ImageSequence模块介绍
- python基础之hello world
- python函数的参数匹配
- Twisted中的putChild和getChild
- vim+python+OpenCV学习六 : 形态学初级
- python模拟登陆