本文介绍了如何限制数字在指定范围内? (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数字限制在一定范围内.目前,我正在执行以下操作:

I want to limit a number to be within a certain range. Currently, I am doing the following:

minN = 1
maxN = 10
n = something() #some return value from a function
n = max(minN, n)
n = min(maxN, n)

这可以将其保留在minNmaxN之内,但是看起来不太好.我该怎么做呢?

This keeps it within minN and maxN, but it doesn't look very nice. How could I do it better?

PS:仅供参考,我正在使用Python 2.6.

PS: FYI, I am using Python 2.6.

推荐答案

def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

或功能上等效的

clamp = lambda n, minn, maxn: max(min(maxn, n), minn)

现在,您使用:

n = clamp(n, 7, 42)

或使其完全清楚:

n = minn if n < minn else maxn if n > maxn else n

更清晰:

def clamp(n, minn, maxn):
    if n < minn:
        return minn
    elif n > maxn:
        return maxn
    else:
        return n

这篇关于如何限制数字在指定范围内? (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 08:27