在序列中循环时,索引位置和对应值可以使用 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
同时循环两个或更多的序列,可以使用 >>> 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.
需要逆向循环序列的话,先正向定位序列,然后调用 >>> for i in reversed(xrange(1, 10, 2)):
... print(i)
...
9
7
5
3
1
要按排序后的顺序循环序列的话,使用 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear
|
Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )
GMT+8, 2024-11-21 18:18 , Processed in 0.017507 second(s), 18 queries .