python enumerate() 函数的使用方法

  列表是最常用的Python数据类型,前段时间看书的时候,发现了enumerate() 函数非常实用,因为才知道下标可以这么容易的使用,总结一下。

class enumerate(object):
"""
Return an enumerate object.
iterable
an object supporting iteration

The enumerate object yields pairs containing a count (from start, which
defaults to zero) and a value yielded by the iterable argument.
这句是重点:
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
"""
 

shope = [['banana',10],

         ['apple',5],
['orange',6],
['watermelon',3],
['strawberry',15]]
方法一:以元组形式取出所有元素
实际中不实用,可以忘记它
for i in enumerate(shope):
print(i)
结果:
(0, ['banana', 10]) <class 'tuple'>
(1, ['apple', 5])
(2, ['orange', 6])
(3, ['watermelon', 3])
(4, ['strawberry', 15])


这里的二和三其实可以说是一种方式,这里为了显示效果,分开了
方法二:
for i in enumerate(shope):
print(i[0],i[1])

结果:
0 ['banana', 10] i[1]:<class 'list'>
1 ['apple', 5]
2 ['orange', 6]
3 ['watermelon', 3]
4 ['strawberry', 15]
方法三:这里相当于把方法一里面的元组里的元素单独取出来再次使用
for i in enumerate(shope):
print(i[1][1])
结果
10
5
6
3
15
原文地址:https://www.cnblogs.com/z977690557/p/10782723.html