在 Python for 循环中创建计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40913678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:11:41  来源:igfitidea点击:

Creating a counter inside a Python for loop

pythonloops

提问by DIGSUM

Obviously, if we do this, the counter will remain at 0 as it is reset at the start of every iteration:

显然,如果我们这样做,计数器将保持为 0,因为它在每次迭代开始时被重置:

for thing in stuff:
    count = 0
    print count
    count =+1
    write_f.write(thing)

But as I have this code inside of function, it does not work to do this either:

但是由于我在函数内部有这段代码,所以这样做也不起作用:

count=0
for thing in stuff:
    print count
    count =+1
    write_f.write(thing)

I have several different indent levels, and no matter how I move count=0about, it either is without effect or throws UnboundLocalError: local variable 'count' referenced before assignment. Is there a way to produce a simple interation counter just inside the for loop itself?

我有几个不同的缩进级别,无论我如何移动count=0,它要么无效,要么抛出UnboundLocalError: local variable 'count' referenced before assignment。有没有办法在 for 循环本身内部生成一个简单的交互计数器?

回答by daniel451

This (creating an extra variable before the for-loop) is notpythonic .

这(在 for 循环之前创建一个额外的变量)不是pythonic 。

The pythonic way to iterate over items while having an extra counter is using enumerate:

在具有额外计数器的同时迭代项目的pythonic方法是使用enumerate

for index, item in enumerate(iterable):
    print(index, item)

So, for example for a list lstthis would be:

因此,例如对于列表,lst这将是:

lst = ["a", "b", "c"]

for index, item in enumerate(lst):
  print(index, item)

...and generate the output:

...并生成输出:

0 a
1 b
2 c


You are strongly recommended to always use Python's built-in functionsfor creating "pythonic solutions" whenever possible. There is also the documentation for enumerate.

强烈建议您尽可能使用 Python 的内置函数来创建“pythonic 解决方案”。还有enumerate的文档。



If you need more information on enumerate, you can look up PEP 279 -- The enumerate() built-in function.

如果您需要有关 enumerate 的更多信息,可以查找PEP 279 -- The enumerate() 内置函数