如何在for循环中为python增加计数器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42753738/
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
How to increment counter in for loop for python?
提问by Reef Rashid
I'm just trying to increment a simple counter in my for loop, but this function always returns 54. I'm guessing it does this because it sees the second counter as a local variable inside the for loop. How can I increment the counter?? I feel like this should be really simple since python is supposedly a straight-forward language. Any help would be greatly appreciated!
我只是想在我的 for 循环中增加一个简单的计数器,但这个函数总是返回 54。我猜它这样做是因为它将第二个计数器视为 for 循环内的局部变量。我怎样才能增加计数器?我觉得这应该很简单,因为 python 应该是一种直接的语言。任何帮助将不胜感激!
for line in train_instances:
counter = 54
a = (line.split(":")[0])[i]
b = (line.split(":")[1])[1]
if ((int(a) == X) and (int(b) == Y)):
counter = counter + 1
return counter
回答by OneCricketeer
Use emumerate
instead .
使用emumerate
来代替。
for counter,line in enumerate(train_instances):
a,b = line.split(":")
Don't increment anything in the loop or reset counter
at all
不增加任何东西在循环或重置counter
所有
回答by Matthew Woodard
You need to move the initial declaration of the counter outside the for loop. Since it's inside, each time you loop through, the counter is getting reset to 54 each time.
您需要将计数器的初始声明移到 for 循环之外。由于它在里面,每次循环时,计数器每次都会重置为 54。
回答by Ajmal Amirzad
It is doing so because the counter variable is in the body of the loop and every time the loop runs, the counter variable is re-declared and assigned the value 54. Why don't you move the counter variable just above the for loop so it returns the right value like in the code below.
这样做是因为计数器变量在循环体中,每次循环运行时,计数器变量都会被重新声明并赋值为 54。为什么不将计数器变量移动到 for 循环的正上方呢?它返回正确的值,如下面的代码所示。
counter = 54
for line in train_instances:
a = (line.split(":")[0])[i]
b = (line.split(":")[1])[1]
if ((int(a) == X) and (int(b) == Y)):
counter = counter + 1
return counter
回答by QB_
You should initialise counter
before the loop. Your current code sets counter
to 54 every loop.
您应该counter
在循环之前初始化。您当前的代码counter
在每个循环中都设置为 54。