在Python中实现自动计数器的建议

在Python中实现自动计数器的建议,python,Python,在Tex中,每次调用引用时,我们都会自动更新计数变量,这样数字计数器就会自动上升 我想在python中为计数器做一些类似的事情,例如,每次我需要计数器时,它已经有了新的值,而无需我添加 A+=1 感谢使用,这是一个迭代器,因此请使用“将对象前进到下一个值”: from itertools import count yourcounter = count() next_counted_value = next(yourcounter) 可以创建lambda来包装函数: yourcounte

在Tex中,每次调用引用时,我们都会自动更新计数变量,这样数字计数器就会自动上升

我想在python中为计数器做一些类似的事情,例如,每次我需要计数器时,它已经有了新的值,而无需我添加

A+=1
感谢使用,这是一个迭代器,因此请使用“将对象前进到下一个值”:

from itertools import count

yourcounter = count()

next_counted_value = next(yourcounter)
可以创建lambda来包装函数:

yourcounter = lambda c=count(): next(c)
或使用:

然后每次调用该对象:

next_counted_value = yourcounter()

甚至是
counter=count()。next
@NiklasB.:确实,我们打算添加这一点,但想明确说明发生了什么。:-)似乎
.next()
不是正确的函数,但
。\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()
@jurl答案是针对Python 2的。现在您想使用
next()
函数。我已经更新了答案。
next_counted_value = yourcounter()