python中enumerate()函数_Python enumerate() 函数
Python中的enumerate函數(shù)主要用于字符串、列表或元組的遍歷時(shí)。一般的,當(dāng)需要對字符串、列表或元組進(jìn)行遍歷的時(shí)候,最簡單的方式如下(這里以list為例):
l = [1,2,3,4,5]
for item in l:
print(item)
程序輸出:
1
2
3
4
5
然而,當(dāng)需要對list中的數(shù)據(jù)進(jìn)行判斷的時(shí)候,比如,list中的第三個(gè)數(shù)字不輸出,此時(shí)就需要使用enumerate函數(shù)了,具體如下:
l = [1,2,3,4,5]
for index, item in enumerate(l):
if index != 2:
print(item)
其實(shí),enumerate函數(shù)把list變成了enumerate(枚舉) 對象,可以使用如下方法查看:
l = [1,2,3,4,5]
print(list(enumerate(l)))
輸出:
[(0, 1), (1, 1), (2, 2), (3, 3), (4, 4)]
其中,第一個(gè)數(shù)字是索引
enumerate函數(shù)還可以指定起始位置,用法是enumerate(sequence, [start=0])
如:
enumerate(l, start=2)#表示指定索引從2開始計(jì)數(shù)
總結(jié)
以上是生活随笔為你收集整理的python中enumerate()函数_Python enumerate() 函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端接收pdf文件_如何实现spring
- 下一篇: python入门第一课_入门第一课 Py