Python one liner确保0< = value< = 1?

时间:2016-04-04 14:20:18

标签: python

我想知道是否有一种压缩此代码的方法:

foo = calculate() # 'calculate' is some kind of function which
                  # could return float values less than 0.0 or more than 1.0
                  # It's here only as a (hopefully) clarification
bar = foo * 5 
if bar < 0:
    bar = 0
elif bar > 1:
    bar = 1
else:
    pass # 'bar' has a good value within the "range"

我知道我可以bar = max(foo * 5, 0)bar = min(foo * 5, 1)但是......有没有办法只在一行中执行此操作?类似于bar = ensure_between(0, foo * 5, 1)之类的东西?

这不是什么大问题,我只是好奇。

提前感谢: - )

1 个答案:

答案 0 :(得分:3)

使用min和max的单行,导致0到1之间的数字,这是你要找的?

foo = max(0, min(foo, 1))

更适合这个例子的是

bar = max(0, min(foo, 1))

编辑:通过删除列表soon指出

来修复