gpt4 book ai didi

python - 如何将参数传递给Python中的可调用迭代器函数?

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:49 25 4
gpt4 key购买 nike

Python 2.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

最佳答案

我不确定你想在这里完成什么,但是

>>> call_iter = iter(lambda:lambda x: x + 1, 100)
>>> next(call_iter)(1)
2

关于python - 如何将参数传递给Python中的可调用迭代器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com