Pythonic维护计数器变量的方法?

Com*_*low 0 python coding-style pep

我有这样的代码:

count = 0

for line in lines:

    #do something with line
    #do something more with line
    #finish doing that thing with line

    count = count + 1
    if count % 10000 == 0:
        print count
Run Code Online (Sandbox Code Playgroud)

这是在python中维护count变量的正确方法吗?我可以让它看起来更好吗?

Ash*_*ary 6

你可以使用enumerate():

for count, line in enumerate(lines):
    #do something here
Run Code Online (Sandbox Code Playgroud)

enumerate()还接受可选的第二个参数start,您可以使用它来指定起始值count.默认值为start0.

帮助enumerate:

>>> help(enumerate)

 |  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]), ...
Run Code Online (Sandbox Code Playgroud)

  • `枚举(line,start = 1)`以匹配OP的帖子 (3认同)