>>> >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
当在序列中循环时,用 enumerate() 函数可以将索引位置和其对应的值同时取出
1 2 3 4 5 6 7
>>> >>> for i, v inenumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
当同时在两个或更多序列中循环时,可以用 zip() 函数将其内元素一一匹配。
1 2 3 4 5 6 7 8 9
>>> >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a inzip(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() 函数
1 2 3 4 5 6 7 8 9
>>> >>> for i inreversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1