Python中的enumerate函数

  • enumerate函数说明:
    • 函数原型:enumerate(sequence, [start=0])
    • 功能:将可循环序列sequence以start开始分别列出序列数据数据下标
    • 即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标

 

enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用enumerate

>>>
>>> product_list =[
...     ('iphone',5800),
...     ('bike',5800),
...     ('mac pro',6400),
...     ('watch',10005),
...     ('coffee',22),
...     ('macbook',10500),
...     ('shirt',50,),
... ]
>>>
>>> for index,item in enumerate(product_list):
...  print(index,item)
...

# 执行结果
0 ('iphone', 5800)
1 ('bike', 5800)
2 ('mac pro', 6400)
3 ('watch', 10005)
4 ('coffee', 22)
5 ('macbook', 10500)
6 ('shirt', 50)
>>> a_list = ["bike","shirt","watch","iphone","mac pro"]
>>>
>>> for index,item in enumerate(a_list):
...  print(index,item)
...
0 bike
1 shirt
2 watch
3 iphone
4 mac pro
原文地址:https://www.cnblogs.com/mingerlcm/p/8193990.html