enumerate(iterable) -> iterator for index, value of iterable
Return an enumerate object. iterable must be an other object that supports
iteration. The enumerate object yields pairs containing a count (from
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]), ...
返回一个enumerate类。可迭代的对象必须是其他支持迭代的类。(这句话保留)。enumerate在得到一个索引
的序列上非常有用
这个是enumerate的定义
def enumerate(collection):
'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'
i = 0
it = iter(collection)
while 1:
yield (i, it.next())
i += 1
|
以前在python中,找出一个序列的index和value,需要这样做:
for i in range(len(alist)):
print i, alist[i]
|
现在,只需要用一个enumerate即可:
for index, value in enumerate(alist):
print index, value
|
可以讲enumerate用到统计文件的行数上
>>> for count, line in enumerate(open('haha')):
... pass
...
>>> print count+1
|
下面还有两种办法
1
>>> count = len(open('haha').readlines())
>>> print count
|
2
>>> len(list(i for line in open('haha')))
|
阅读(1311) | 评论(0) | 转发(0) |