1、内置函数enumerate(iterable[, start])的官方说明:
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]), ...
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
- enumerate在字典上是枚举、列举的意思
- 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
- enumerate多用于在for循环中得到计数,第一个参数iterable传入可迭代对象列表或者元组,字符串等;第二个参数start为可选参数,指定起始index数。
2、实例详解
对于一个seq可迭代对象进行enumerate操作,enumerate(seq)得到:
input:enumerate(seq)
output:(0, seq[0]), (1, seq[1]), (2, seq[2])
对列表 seqs = [1,2,3,4,7,8,9] 进行枚举,既要得到遍历索引又要遍历元素时:
In [2]: seqs = [1,2,3,4,7,8,9]
In [3]: enumerate(seqs)
Out[3]: <enumerate at 0x1ba9c822b88>
In [4]: list(enumerate(seqs))
Out[4]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 7), (5, 8), (6, 9)]
如果指定起始的index值为1:
In [5]: list(enumerate(seqs,1))
Out[5]: [(1, 1), (2, 2), (3, 3), (4, 4), (5, 7), (6, 8), (7, 9)]
如果要统计文件的行数,可以这样写:
count = len(open(filepath, 'r').readlines())
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作;可以利用enumerate():
count = 0
for index, line in enumerate(open(filepath,'r')):
count += 1

2万+

被折叠的 条评论
为什么被折叠?



