本文,介绍python中enumerate类的使用。
>>> help(enumerate)
Help on class enumerate in module __builtin__:class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
1》参数是列表
>>> l=['one','two','three']
>>> e=enumerate(l)
>>> e
<enumerate object at 0x069FF6E8>
>>> list(e)
[(0, 'one'), (1, 'two'), (2, 'three')]
>>> e=enumerate(l) #新生成一个e
>>> for i,item in e: # in后边的e必须是新生成的,原因请参考: python 内置函数 reversed() 文章中的相关解释。。。
... print i,item
...
0 one
1 two
2 three
2》参数是元组
>>> for i,v in enumerate((3,4,5,6,7)): #默认从0开始计数
print i,v
0 3
1 4
2 5
3 6
4 7
>>> for i,v in enumerate((3,4,5,6,7),1): #指定从1开始计数
print i,v
1 3
2 4
3 5
4 6
5 7
3》参数是字典
>>> d
{'a': 1, 'b': 2}
>>> e=enumerate(d)
>>> e
<enumerate object at 0x06A81788>
>>> list(e)
[(0, 'a'), (1, 'b')]
>>> for i,key in enumerate(d): # in 后边新生成一个枚举对象
... print i,key
...
0 a
1 b
4》参数是字符串
>>> s='python'
>>> e=enumerate(s)
>>> e
<enumerate object at 0x069FF990>
>>> list(e)
[(0, 'p'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]
>>> for i,str in enumerate(s): # in 后边是新生成的枚举对象
... print i,str
...
0 p
1 y
2 t
3 h
4 o
5 n
>>> import string
>>> s=string.ascii_uppercase
>>> s
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> e=enumerate(s)
>>> e
<enumerate object at 0x069FF710>
>>> list(e)
[(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E'), (5, 'F'), (6, 'G'), (7, 'H'), (8, 'I'), (9, 'J'), (10, 'K'), (11, 'L'), (12, 'M'), (13, 'N'), (14, 'O'), (15, 'P'), (16, 'Q'), (17, 'R'), (18, 'S'), (19, 'T'), (20, 'U'),
(21, 'V'), (22, 'W'), (23, 'X'), (24, 'Y'), (25, 'Z')]
>>> for i,str in enumerate(s): #新生成一个枚举对象... print i,str
...
0 A
1 B
2 C
3 D
4 E
5 F
6 G
7 H
8 I
9 J
10 K
11 L
12 M
13 N
14 O
15 P
16 Q
17 R
18 S
19 T
20 U
21 V
22 W
23 X
24 Y
25 Z
最后,我们看一个enumerate的应用实例,该实例中,s 是个字符串,只包含 0 和 1,要把0都找出来:
1》不使用enumerate(),如下:
def find_0(s):
d={}
for i in range(len(s)):
if s[i]=='0':
d[i]=int(s[i]) # d[i]=0
return d
>>> find_0('10010101')
{1: 0, 2: 0, 4: 0, 6: 0}
2》使用enumerate(),如下:
def find_0(s): #返回列表return [(index,int(value)) for index, value in enumerate(s) if value == '0']
>>> find_0('1000101')
[(1, 0), (2, 0), (3, 0), (5, 0)]
def find_0(s): #返回生成器对象
return ((index,0) for index, value in enumerate(s) if value == '0')
>>> find_0('1000110')
<generator object <genexpr> at 0x06A90B20>
>>> list(find_0('1000110'))
[(1, 0), (2, 0), (3, 0), (6, 0)]
(完)