您的位置:首页 > 编程语言 > Python开发

Python enumerate 使用技巧

2016-01-31 14:10 543 查看
  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: