When I am looping over a file using the construct below, I also want the current line number.
当我使用下面的构造对一个文件进行循环时,我还需要当前行号。
with codecs.open(filename, 'rb', 'utf8' ) as f:
retval = []
for line in f:
process(line)
Does something akin to this exist ?
类似的东西存在吗?
for line, lineno in f:
2 个解决方案
#1
10
for lineno, line in enumerate(f, start=1):
If you are stuck on a version of Python that doesn't allow you to set the starting number for enumerate
(this feature was added in Python 2.6), and you want to use this feature, the best solution is probably to provide an implementation that does, rather than adjusting the index returned by the built-in function. Here is such an implementation.
如果你困在一个版本的Python不允许您设置的起始数量列举(此功能是添加在Python 2.6),和你想使用此功能,可能最好的解决方案是提供一个实现,而不是调整索引返回的内置函数。这里有一个这样的实现。
def enumerate(iterable, start=0):
for item in iterable:
yield start, item
start += 1
#2
1
If you are using Python2.6+, kindall's answer covers it
如果您使用的是Python2.6+,那么,kindall的答案涵盖了它。
Python2.5 and earlier don't support the second argument to enumertate, so you need to use something like this
Python2.5和更早的版本不支持第二个要枚举的参数,所以您需要使用类似的东西
for i, line in enumerate(f):
lineno = i+1
or
或
for lineno, line in ((i+1,j) for i,j in enumerate(f)):
Unless you are ok with the first line being number 0
除非你觉得第一行是0
#1
10
for lineno, line in enumerate(f, start=1):
If you are stuck on a version of Python that doesn't allow you to set the starting number for enumerate
(this feature was added in Python 2.6), and you want to use this feature, the best solution is probably to provide an implementation that does, rather than adjusting the index returned by the built-in function. Here is such an implementation.
如果你困在一个版本的Python不允许您设置的起始数量列举(此功能是添加在Python 2.6),和你想使用此功能,可能最好的解决方案是提供一个实现,而不是调整索引返回的内置函数。这里有一个这样的实现。
def enumerate(iterable, start=0):
for item in iterable:
yield start, item
start += 1
#2
1
If you are using Python2.6+, kindall's answer covers it
如果您使用的是Python2.6+,那么,kindall的答案涵盖了它。
Python2.5 and earlier don't support the second argument to enumertate, so you need to use something like this
Python2.5和更早的版本不支持第二个要枚举的参数,所以您需要使用类似的东西
for i, line in enumerate(f):
lineno = i+1
or
或
for lineno, line in ((i+1,j) for i,j in enumerate(f)):
Unless you are ok with the first line being number 0
除非你觉得第一行是0