enumerate函数用于遍历序列中的元素以及它们的下标,多用于在for循环中得到计数,enumerate参数为可遍历的变量,如 字符串,列表等
一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:
测试一下:
1.没有使用enumerate函数程序及运行结果。
>>> list=['av','ac','ad','af','ax']
>>> for i in range (0,len(list)):
... print('i',i)
... print('list',list[i])
...
i 0
list av
i 1
list ac
i 2
list ad
i 3
list af
i 4
list ax
>>>
但是这种方法有些累赘,使用内置enumerrate函数会有更加直接,优美的做法,先看看enumerate的定义:
def enumerate(collection):
'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'
i = 0
it = iter(collection)
while 1:
yield (i, it.next())
i += 1
使用内置enumerrate函数的程序运行结果
>>> list=['av','ac','ad','af','ax']
>>> for index,text in enumerate(list):
... print('index',index)
... print('text',text)
...
index 0
text av
index 1
text ac
index 2
text ad
index 3
text af
index 4
text ax
>>>
与上面的代码相比,他们具有同样的输出功能。我感觉下面这个比较简单,简洁。这才是python的特性。
本文介绍了Python中内置的enumerate函数,它能同时遍历列表、数组的下标和元素,提升代码简洁性。通过对比传统方法和使用enumerate的例子,展示了其在优化代码结构方面的优势。

2290

被折叠的 条评论
为什么被折叠?



