Home  >  Article  >  Backend Development  >  python中使用enumerate函数遍历元素实例

python中使用enumerate函数遍历元素实例

WBOY
WBOYOriginal
2016-06-06 11:31:061247browse

这个是python的一个内建函数,看书的时候发现了他,mark一下
当我们既需要遍历索引同时需要遍历元素的时候,可以考虑使用enumerate函数,enumerate函数接受一个可遍历的对象,如列表、字符串

比如我们有一个["one","two","there"]的列表,我们需要在列表的每个元素前面加上他的编号

代码如下:


i = 0
seq = ["one","two","three"]
for element in seq:
 seq[i] = '%d: %s' % (i, seq[i])
 i += 1
print seq

['0: one', '1: two', '2: three']

使用enumerate函数,我们可以简化我们的代码,省去定义计数用的临时变量

代码如下:


seq = ["one","two","three"]
for i, element in enumerate(seq):
 seq[i] = '%d: %s' % (i, seq[i])
print seq

['0: one', '1: two', '2: three']


好戏还没有结束,python的魅力正在于此,我们来个Phthonic的写法

代码如下:


seq = ["one","two","three"]
print ['%d: %s'% (i,element) for i,element in enumerate(seq) ]

['0: one', '1: two', '2: three']


好了,python的遍历技术非常灵活,几句话是讲不完的,要熄灯了,洗洗睡了
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn