Pythonic方法用一组参数调用一个函数,直到它返回任何但是没有的东西

时间:2016-07-10 16:39:53

标签: python python-2.7

我知道使用for循环并调用我的函数,直到我得不到None作为返回值,但我正在寻找一些内置的python可以帮助到这里。

e.g。 - iter(myfunc(), None)它会调用myfunc(),直到它返回None

我正在寻找与此完全相反的代码,例如 - iter(myfunc(), not None), Call myfunc()直到它返回None

之外的任何内容

提前致谢..

4 个答案:

答案 0 :(得分:3)

只有三行:

x = None
while x is None:
    x = f()

答案 1 :(得分:2)

不要为所有东西寻找内置物。在我看来,即使通常的两个论点形式的iter也不值得使用,因为它不是一个众所周知的特征,这使得大多数人更难阅读。只需保持简单明了。额外的一两行不会受到伤害。

while True:
    x = myfunc()
    if x is not None:
        break

答案 2 :(得分:1)

没有现成的内置功能,但构建生成器功能非常容易:

def iter_while_none(f):
    while True:
        value = f()
        if value is not None:
            return
        yield value

虽然产生的价值不是那么有趣;毕竟,每次都是None

答案 3 :(得分:1)

这个答案有点像Python的力量。我感到沮丧的是,iter 2-arity表格没有为第二个参数提供函数。

但如果你足够疯狂,那就确实如此。请参阅,您可以重新定义对象的相等性,如下所示:

class Something:
    def __eq__(self, other):
        self.lastother = other
        return other is not None

sentinel = Something()
myiter = iter(myfunc, sentinel)
for nope in myiter:
    pass
match = sentinel.lastother

有。请享用。 Python非常惊人,你可以通过这种方式颠覆平等的定义。玩得开心冲进城堡!