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.
逆向循环序列时,先正向定位序列,然后调用 reversed() 函数:
>>>
for i in reversed(range(1, 10, 2)):
… print(i)
…
9
7
5
3
1
按指定顺序循环序列,可以用 sorted() 函数,在不改动原序列的基础上,返回一个重新的序列:
>>>
basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’]
for i in sorted(basket):
… print(i)
…
apple
apple
banana
orange
orange
pear
使用 set() 去除序列中的重复元素。使用 sorted() 加 set() 则按排序后的顺序,循环遍历序列中的唯一元素:
>>>
basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’]
for f in sorted(set(basket)):
… print(f)
…
apple