Python的循环技术
在循环 dictionary(字典)型数据时,键与值(Key , Value)可以在一个 for 循环中使用 dictinary 的iteritems() 函数同时检索到,如下:
>>> knights = {'gallahad': 'the pure','robin':'the brave'}
>>> for k,v in knights.iteritems(): print k,v
...
gallahad the pure
robin the brave
当我们循环一个序列时,元素的位置与元素值本身也可以同时被检索到,这个时候我们就需要使用enumerate() 函数:
>>> seq = ['tic', 'tac', 'toe']
>>> for i,v in enumerate(seq): print i,v
...
0 tic
1 tac
2 toe
如果同时将两个序列进行检索,我们可以使用 zip() 函数将这两个序列进行配对,然后再在同一个 for 循环中检索:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['costony', '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 costony.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.