python enumerate() 函數的使用方法
阿新 • • 發佈:2019-04-28
lis range The pre tin 時間 再次 數據類型 val
列表是最常用的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
python enumerate() 函數的使用方法