5.6 循环技巧 Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method.

在字典中循环时,关键字和对应的值可以使用 iteritems() 方法同时解读出来。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

在序列中循环时,索引位置和对应值可以使用enumerate() 函数同时得到。

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print i, v
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

同时循环两个或更多的序列,可以使用 zip() 整体解读。

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print 'What is your %s?  It is %s.' % (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.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

打算反向循环序列时, 可以先计算出序列, 然后调用 reversed() 函数.

>>> for i in reversed(xrange(1,10,2)):
...     print i
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

要按次序循环一个序列, 用 sorted() 函数, 它传回一个新的排好序的序列. 而原先的序列则保留不变.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print f
...
apple
banana
orange
pear