您的位置:首页 > 编程语言 > Python开发

python enumerate用法

2017-07-04 10:05 423 查看
原文:http://blog.csdn.net/xyw_blog/article/details/18401237

python中我们可以这样遍历数组(字符串、元组、列表等):

[python] view
plain copy

 print?

for item in sequence:  

       process(item)  

这种方式,我们只获得sequence中的值,没有获得索引

[python] view
plain copy

 print?

for index in range(len(sequence)):  

    process(sequence[index])  

这种方式可以获得索引以及对应的值。但是这显得很繁琐。python其实提供了内置的enumerate函数可以同时获得索引和值,可以这样实现:

[python] view
plain copy

 print?

for index, key in enumerate(sequence):  

      process(index, key)  

如果你想对sequence中的元素作逆置后处理,可以:

[python] view
plain copy

 print?

for index, key in enumerate(sequence[::-1]):  

     process(index, key)  

举例说明:

[python] view
plain copy

 print?

>>> seq = 'hello'  

>>> for i,key in enumerate(seq):  

...     print 'seq[%d]=%s' % (i, key)  

...   

seq[0]=h  

seq[1]=e  

seq[2]=l  

seq[3]=l  

seq[4]=o  

[python] view
plain copy

 print?

>>> seq = ['a','b','c','d']  

>>> for i,key in enumerate(seq):  

...     print 'seq[%d]=%s' % (i, key)  

...   

seq[0]=a  

seq[1]=b  

seq[2]=c  

seq[3]=d  

[python] view
plain copy

 print?

>>> seq = ['a','b','c','d']  

>>> for i,key in enumerate(seq[::-1]):  

...     print 'seq[%d]=%s' % (i, key)  

...   

seq[0]=d  

seq[1]=c  

seq[2]=b  

seq[3]=a
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: