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