Python3.3.2 官方文档教程---遍历技巧
来源:互联网 发布:编程cs 编辑:程序博客网 时间:2024/05/13 23:36
3.6 遍历技巧
当通过字典遍历数据时,用items()方法就可以同时把关键字和相对应的值从字典中取出。
>>> knights = {’gallahad’: ’the pure’, ’robin’: ’the brave’}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
当用序列遍历数据时,用enumerate()可以同时把位置索引和对应的值得到。
>>> for i, v in enumerate([’tic’, ’tac’, ’toe’]):
... print(i, v)
...
0 tic
1 tac
2 toe
想要同时遍历两个或多个序列时,可以用方法zip()把属性整合起来。
>>> questions = [’name’, ’quest’, ’favorite color’]
>>> answers = [’lancelot’, ’the holy grail’, ’blue’]
>>> for q, a in zip(questions, answers):
... print(’What is your {0}? It is {1}.’.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
想要倒叙遍历序列,首先正序指定遍历序列,然后调用方法reversed().
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
想要有序的遍历列表,用方法sorted()可以返回一个新的有序列表而不改变原先列表。
>>> basket = [’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’]
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
Pear
- Python3.3.2 官方文档教程---遍历技巧
- Python3.3.2 官方文档教程---字典
- Python3.3.2 官方文档教程---深入条件控制
- Python3.2官方文档教程--数字
- Python3.2官方文档教程--字符串
- Python3.2官方文档教程- 列表
- Python3.2 官方文档教程---编码风格
- Python3.2 官方文档教程--列表
- Python3.2官方文档教程---Set集合
- python3.2官方文档教程--模块
- Python3.2官方文档教程--深入模块
- Python3.2官方文档教程--包
- Python3.2官方文档教程---格式化输出
- 格式化输出Python3.2官方文档教程
- Python3.2官方文档教程--方法定义--关键字参数
- Python3.2官方文档教程--其余参数形式
- Python3.2官方文档教程---元组与序列
- python3.2.3官方文档翻译
- ceshi
- 【LeetCode】Reverse Words in a String
- 黑马程序员—Java集合框架(Set、HashSet、TreeSet)
- 谷歌android CTS认证
- listView的问题
- Python3.3.2 官方文档教程---遍历技巧
- 详谈Struts2的核心概念(下)
- 媒体称习近平确立便服礼服新标准(图)
- 产品矩阵,会是移动互联网的新入口吗?
- 在try中写了return,后面又写了finally,是先执行return还是先执行fianlly
- (原创)FragmentTabHost的应用(fragment学习系列文章之二)
- xfire的jaxb2实例
- 酒店经典
- 学习笔记_web——HTML