python enumerate用法

本文介绍Python中使用enumerate函数遍历序列的方法,包括如何获取索引和元素,以及逆序处理序列的技术。

原文:http://blog.youkuaiyun.com/xyw_blog/article/details/18401237

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

[python]  view plain  copy
 print ?
  1. for item in sequence:  
  2.        process(item)  
这种方式,我们只获得sequence中的值,没有获得索引

[python]  view plain  copy
 print ?
  1. for index in range(len(sequence)):  
  2.     process(sequence[index])  
这种方式可以获得索引以及对应的值。但是这显得很繁琐。python其实提供了内置的enumerate函数可以同时获得索引和值,可以这样实现:

[python]  view plain  copy
 print ?
  1. for index, key in enumerate(sequence):  
  2.       process(index, key)  
如果你想对sequence中的元素作逆置后处理,可以:

[python]  view plain  copy
 print ?
  1. for index, key in enumerate(sequence[::-1]):  
  2.      process(index, key)  
举例说明:

[python]  view plain  copy
 print ?
  1. >>> seq = 'hello'  
  2. >>> for i,key in enumerate(seq):  
  3. ...     print 'seq[%d]=%s' % (i, key)  
  4. ...   
  5. seq[0]=h  
  6. seq[1]=e  
  7. seq[2]=l  
  8. seq[3]=l  
  9. seq[4]=o  
[python]  view plain  copy
 print ?
  1. >>> seq = ['a','b','c','d']  
  2. >>> for i,key in enumerate(seq):  
  3. ...     print 'seq[%d]=%s' % (i, key)  
  4. ...   
  5. seq[0]=a  
  6. seq[1]=b  
  7. seq[2]=c  
  8. seq[3]=d  
[python]  view plain  copy
 print ?
  1. >>> seq = ['a','b','c','d']  
  2. >>> for i,key in enumerate(seq[::-1]):  
  3. ...     print 'seq[%d]=%s' % (i, key)  
  4. ...   
  5. seq[0]=d  
  6. seq[1]=c  
  7. seq[2]=b  
  8. seq[3]=a  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值