knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k,v in knights.items():
print(k,v)
-------输出如下-------------------------
robin the brave
gallahad the pure
在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到。
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i,v)
------输出如下------------------------------
0 tic
1 tac
2 toe
同时循环两个或更多的序列,可以使用 zip() 整体打包。
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q,a in zip(questions,answers):
print("{0},{1}".format(q,a))
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
------输出如下----------------------------------
apple
banana
orange
pear