查找不满足条件的最小非负整数



我有函数f,它接受int并返回bool。我想找到最小非负整数xf(x)False。我怎样才能以最pythonic的方式(理想情况下是一行)来做到这一点?


这是我现在的做法:

x = 0
while f(x):
x += 1
print(x)

我想要这样的东西:

x = <perfect one line expression>
print(x)

在这里,使用next

from itertools import count
x = next(i for i in count() if not f(i))

演示:

>>> def f(x):
...     return (x - 42)**2
... 
>>> next(i for i in count() if not f(i))
42

具有itertools.filterfalseitertools.count的类似功能方法可能是

from itertools import filterfalse, count
x = next(filterfalse(f, count()))

或者你可以用dropwhile替换filterfalse,虽然性能相似,但在Python 2和3中保持相同的语法(感谢rici)。

from itertools import dropwhile, count
x = next(dropwhile(f, count()))

如果你想要一行没有导入,一种方法可能是列表推导(Python 2.7/PyPy):

def f(x):
return True if x == 5 else False
x = [g(0) for g in [lambda x: x if f(x) else g(x+1)]][0]
print(x)

最新更新