示例:
test.txt内容:
aaaa
bbbb
cccc
file_object = open(r'c:\test.txt')
try:
for line_num, context in enumerate(file_object):
print str(line_num) + ':' + context
finally:
file_object.close()
# 带序号输出
0:aaaa
1:bbbb
2:cccc
doc:
-
enumerate
(
sequence
[,
start=0
]
)
-
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. Thenext() method of the iterator returned byenumerate() returns a tuple containing a count (fromstart which defaults to 0) and the values obtained from iterating oversequence:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Equivalent to:
def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
New in version 2.3.
Changed in version 2.6: The start parameter was added.