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
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
相关文章推荐
- python enumerate 用法
- python enumerate用法
- python enumerate()用法
- python天天进步(7)--enumerate用法
- python中的enumerate()函数用法
- python --enumerate用法
- python enumerate 函数用法
- python enumerate 用法
- python enumerate用法总结
- python enumerate用法总结
- python enumerate 用法
- Python中enumerate用法
- python enumerate 用法
- python enumerate用法
- python中enumerate的用法实例解析
- python enumerate 用法
- python --enumerate用法
- python --enumerate用法
- Python enumerate 用法
- Python中enumerate()函数的用法