【问题标题】:Pythonic way of maintaining counter variables?维护计数器变量的Pythonic方式?
【发布时间】:2013-06-24 11:59:17
【问题描述】:

我有这样的代码:

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

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

【问题讨论】:

标签: python coding-style pep


【解决方案1】:

你可以使用enumerate():

for count, line in enumerate(lines):
    #do something here

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

关于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]), ...

【讨论】:

  • enumerate(line, start=1) 匹配 OP 的帖子
  • 假设他在数行数......他可能在数行数in的东西(不太可能,但可能)
  • 可以枚举带生成器吗?
  • enumerate() 会影响我的代码性能吗? @AshwiniChaudhary
  • @user 是的,它可能会稍微慢一些,因为enumerate 返回一个迭代器,并且要从迭代器中获取一个项目,每次都需要调用next()。但差异可以忽略不计。而enumerate() 更符合 Python 风格。
猜你喜欢
  • 2018-03-18
  • 1970-01-01
  • 2021-06-07
  • 2011-04-01
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
相关资源
最近更新 更多