如何强制一个值在一个范围内?
How to force a value to be within a range?
最"pythonic"的方法是什么?
x = some_value
bounds = [lower_bound, upper_bound]
if x < bounds[0]:
x = bounds[0]
if x > bounds[1]:
x = bounds[1]
我觉得这看起来好多了
x = sorted([lower_bound, x, upper_bound])[1]
但是如果要考虑性能,那么if/elif
是最好的实现方式。
你可以这样做:
x = max(min(some_value, upper_bound), lower_bound)
这是 pythonic,因为它是一个简洁的单行代码,而且比创建列表并对其排序更有效。
如果你不关心这个值是多少只要在一定范围内即可:
>>> import random
>>> random.choice(range(lower_bound, upper_bound))
...and sometimes get carried away with finding a tricky way to do do
something in one line.
编程最重要的是你真正理解你要解决的问题。然后你想写代码,可以阅读。所以,pythonic并不意味着它是单行的...
这并不丑陋或糟糕Python:
if x < lb:
x = lb
elif x > ub:
x = ub
这就是我建议的写法 Naman Sogani 建议的方式。
_, x, _ = sorted([lb, x, ub])
最"pythonic"的方法是什么?
x = some_value
bounds = [lower_bound, upper_bound]
if x < bounds[0]:
x = bounds[0]
if x > bounds[1]:
x = bounds[1]
我觉得这看起来好多了
x = sorted([lower_bound, x, upper_bound])[1]
但是如果要考虑性能,那么if/elif
是最好的实现方式。
你可以这样做:
x = max(min(some_value, upper_bound), lower_bound)
这是 pythonic,因为它是一个简洁的单行代码,而且比创建列表并对其排序更有效。
如果你不关心这个值是多少只要在一定范围内即可:
>>> import random
>>> random.choice(range(lower_bound, upper_bound))
...and sometimes get carried away with finding a tricky way to do do something in one line.
编程最重要的是你真正理解你要解决的问题。然后你想写代码,可以阅读。所以,pythonic并不意味着它是单行的...
这并不丑陋或糟糕Python:
if x < lb:
x = lb
elif x > ub:
x = ub
这就是我建议的写法 Naman Sogani 建议的方式。
_, x, _ = sorted([lb, x, ub])