Python基础教程——5条件、循环和其他语句
来源:互联网 发布:设计图标的软件 编辑:程序博客网 时间:2024/05/21 08:00
简单的例子
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
复杂些的例子——找出首字母相同的男孩和女孩
>>> girls = ['alice','bernice','clarice']
>>> boys = ['chris','arnold','bob']
>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
效率更高的实现
>>> girls = ['alice','bernice','clarice']
>>> boys = ['chris','arnold','bob']
>>> letterGirls = {}
>>> for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
>>> print [b + '+' + g for b in boys for g in letterGirls[b[0]]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
>>> letterGirls
{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
摘自《Python基础教程》
- Python基础教程——5条件、循环和其他语句
- Python基础教程笔记——条件,循环和其他语句
- Python基础教程笔记——条件,循环和其他语句
- Python基础教程(5)条件、循环和其他语句
- Python学习笔记【五】——《python基础教程》:: 条件、循环和其他语句
- 第五章-条件、循环和其他语句——python基础教程(第二版)笔记
- Python基础教程第五章学习笔记——条件、循环和其他语句
- 《Python基础教程》学习笔记 Chap5 条件、循环和其他语句
- Python基础教程之第5章 条件, 循环和其他语句
- Python——条件、循环和其他语句
- 【python】第五章——条件、循环和其他语句
- Python——条件、循环和其他语句
- Python——条件、循环和其他语句
- Python基础教程学习笔记----第五章 条件、循环和其他语句
- <<Python基础教程>>学习笔记 | 第05章 | 条件、循环和其他语句
- 【Python基础教程笔记(二)】字典,条件,循环和其他语句
- [Python 05] 条件,循环和其他语句
- python 条件,循环和其他语句
- Iphone开发基础篇(五)-ObjectC之内存管理
- 数据时代
- 一个完全超出数学一切能力的问题
- CString详解以及CString转换成char*
- Linux网络协议栈--ip_append_data函数分析
- Python基础教程——5条件、循环和其他语句
- Android 中关于 【Cursor】 类的介绍
- 遍历目录下文件夹并删除
- centos内核编译
- C++ 位操作
- 通过js根据接收的数据控制select标签的默认选择项
- Android 性能测试之TraceView的使用
- Myeclipse的使用方法-导入、导出Java 项目
- WaitForSingleObject的用法