enumerate() 是Python内建的函数,能让打印的结果更清晰,不管是列表,元组,字典,enumerate()都可以帮你完成,在某些需求下还是非常好用的。
>>> a = [1,2,3]
for index,value in enumerate(a):
print(index,value)
其实enumerate()不仅可用于列表,还可在字典和元组中使用:
>>> b = {'apple':7,'pear':5,'strawberry':3,'orange':1}
for index,value in enumerate(b.keys()):
print(index,value)
(0, 'orange')
(1, 'strawberry')
(2, 'pear')
(3, 'apple')
另外默认enumerate() 打印的索引默认是从0开始的,如果你不喜欢,没关系,当你指定第二个整数参数,它就会取代0:
>>> for index,value in enumerate(vehicle, 100):
print(index,value)
(100, 'bicycle')
(101, 'car')
(102, 'bus')
不喜欢纵列打印的还可以这样:
>>> choices = ['pizza', 'pasta', 'salad', 'nachos']
c = list(enumerate(choices))
print(c)
[(0, 'pizza'), (1, 'pasta'), (2, 'salad'), (3, 'nachos')]
更多参考这里:https://docs.python.org/2/library/functions.html#enumerate
手机扫一扫
移动阅读更方便
你可能感兴趣的文章