30秒学会 Python 片段 · 2022年6月28日

30秒学会 Python 片段 – Clamp number

Clamps num within the inclusive range specified by the boundary values.

  • If num falls within the range (a, b), return num.
  • Otherwise, return the nearest number in the range.

代码实现

def clamp_number(num, a, b):
  return max(min(num, max(a, b)), min(a, b))

使用样例

clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1

翻译自:https://www.30secondsofcode.org/python/s/clamp-number