如何编写一个只在每次调用时返回递增数字的函数?
print counter() # 0
print counter() # 1
print counter() # 2
print counter() # 3
etc
Run Code Online (Sandbox Code Playgroud)
为清楚起见,我不是在寻找发电机(虽然答案可能会使用它).该函数应返回一个整数,而不是一个可迭代的对象.我也不是在寻找涉及全局或其他共享变量(类,函数属性等)的解决方案.
请参阅http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html,了解有关此事的一些有用见解.
Sve*_*ach 11
您不需要实现该功能 - 它已经存在:
counter = itertools.count().next
Run Code Online (Sandbox Code Playgroud)
或者在Python 3.x中
counter = itertools.count().__next__
Run Code Online (Sandbox Code Playgroud)
更一般地说,如果你想要一个具有附加状态的可调用,有几种解决方案:
一类:
class Counter(object):
def __init__(self, start=0):
self.count = 0
def __call__(self):
val = self.count
self.count += 1
return val
Run Code Online (Sandbox Code Playgroud)一个可变的默认参数:
def counter(_count=[0]):
val = _count[0]
_count[0] += 1
return val
Run Code Online (Sandbox Code Playgroud)关闭:
def make_counter(start=0):
count = [start]
def counter():
val = count[0]
count[0] += 1
return val
return counter
Run Code Online (Sandbox Code Playgroud)
在Python 3.x中,您不再需要上面的hack使用列表,因为您可以使用nonlocal
声明:
def make_counter(start=0):
count = start
def counter():
nonlocal count
val = count
count += 1
return val
return counter
Run Code Online (Sandbox Code Playgroud)函数参数:
def counter():
val = counter.count
counter.count += 1
return val
counter.count = 0
Run Code Online (Sandbox Code Playgroud)发电机:
def count(start=0):
while True:
yield start
start += 1
counter = count().next ## or .__next__ in Python 3.x
Run Code Online (Sandbox Code Playgroud)当然,所有这些解决方案都必须在某处存储当前计数.
简而言之,
from itertools import count
counter = lambda c=count(): next(c)
Run Code Online (Sandbox Code Playgroud)