5.6 循环技术
当循环字典的时候,key 和对应的值可以通过 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.
在一个相反的序列内循环的时候,首先指定循环方向的序列,然后调用 reverse()
函数。
>>> 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
在你一边循环一个列表的时一边候改变它,有时候着具有吸引力。但是创建一个新列表会更简单安全。
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
... if not math.isnan(value):
... filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]