Python2.6.2
>>> call_iter = iter(lambda x: x + 1, 100)
>>> call_iter.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (0 given)
我想把参数传递给lambda x:x + 1
。
更新:我认为上面的例子很难理解。
我想知道python中是否有像myiter这样的内置函数:
class myiter:
def __init__(self, callable, initial, sentinel):
self.value = initial
self.callable = callable
self.sentinel = sentinel
def __iter__(self):
return self
def next(self):
if self.value == self.sentinel:
raise StopIteration
else:
# calculate next value from prev value
self.value = self.callable(self.value)
return self.value
if __name__ == '__main__':
call_iter = myiter(lambda x:x + 1, 0, 100)
for i in call_iter:
print i
我想你想要的是:
要将参数传递给lambda函数,需要将lambda映射到iterable like range(100)或[2,4,5]
您尝试使用的iter形式只接受一个0参数函数。下面仅作说明;不要这样做。
一般来说,这种形式的
iter
不是很有用。它需要某种在调用之间保持状态的可调用类型。例如,可以传递文件对象的readline
方法,如docs中所建议的。但总的来说,有更好的方法可以做到这一点。例如,假设您创建了这样一个类:它很可爱,但是如果您必须创建一个应该是可iterable的类,那么您也可以通过给它一个}
next
方法和一个__iter__
方法使它成为一个真正的迭代器。相反,如果不创建类,只需使用^{我不知道你想在这里完成什么,但是
相关问题 更多 >
编程相关推荐