Python 中遍历序列中元素和下标

时间:2022-03-29 21:47:10

enumerate 函数用于遍历序列中的元素以及它们的下标

for  i,v in  enumerate(['tic','tac','toe']):
print i,v #0 tic
#1 tac
#2 toe for i,j in enumerate(('a','b','c')):
print i,j #0 a
#1 b
#2 c for i,j in enumerate({'a':1,'b':2}):
print i,j #0 a
#1 b

遍历字典的key和value

knights={'galahad':'the pure','robin':'the brave'}
for k,v in knights.iteritems():
print k,v #galahad the pure
#robin the brave