如何在python中向可调用迭代器的函数传递参数?

2024-09-28 20:47:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: lambdainselfreturnifvaluedefcall
3条回答

我想你想要的是:

call_iter = iter(map(lambda x: x + 1, range(100)))
>>> call_iter.next()
1
>>> call_iter.next()
2
>>> call_iter.next()
3
>>> 

要将参数传递给lambda函数,需要将lambda映射到iterable like range(100)或[2,4,5]

您尝试使用的iter形式只接受一个0参数函数。下面仅作说明;不要这样做。

>>> x = 0
>>> def counter():
...     global x
...     x += 1
...     return x
... 
>>> list(iter(counter, 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

一般来说,这种形式的iter不是很有用。它需要某种在调用之间保持状态的可调用类型。例如,可以传递文件对象的readline方法,如docs中所建议的。但总的来说,有更好的方法可以做到这一点。例如,假设您创建了这样一个类:

>>> class Incrementer(object):
...     def __init__(self):
...         self.state = 0
...     def __call__(self):
...         rval = self.state
...         self.state += 1
...         return rval
... 
>>> list(iter(Incrementer(), 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

它很可爱,但是如果您必须创建一个应该是可iterable的类,那么您也可以通过给它一个next方法和一个__iter__方法使它成为一个真正的迭代器。相反,如果不创建类,只需使用^{}

我不知道你想在这里完成什么,但是

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

相关问题 更多 >