如何将整数钳位到某个范围? [英] How to clamp an integer to some range?

查看:87
本文介绍了如何将整数钳位到某个范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

new_index = index + offset
if new_index < 0:
    new_index = 0
if new_index >= len(mylist):
    new_index = len(mylist) - 1
return mylist[new_index]

基本上,我计算一个新索引,并使用该索引从列表中查找某些元素.为了确保索引在列表的范围内,我需要编写这2条if语句,这些语句分散在4行中.这很冗长,有点丑陋……我敢说,这很非pythonic .

Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds of the list, I needed to write those 2 if statements spread into 4 lines. That's quite verbose, a bit ugly... Dare I say, it's quite un-pythonic.

还有其他更简单,更紧凑的解决方案吗?(还有更多的 pythonic )

是的,我知道我可以在一行中使用if else,但是它不可读:

Yes, i know I can use if else in one line, but it is not readable:

new_index = 0 if new_index < 0 else len(mylist) - 1 if new_index >= len(mylist) else new_index

我也知道我可以将max()min()链接在一起.它更紧凑,但是我觉得它有点晦涩难懂,如果我输入错误的话,更难发现错误.换句话说,我觉得它不是很简单.

I also know I can chain max() and min() together. It's more compact, but I feel it's kinda obscure, more difficult to find bugs if I type it wrong. In other words, I don't find it very straightforward.

new_index = max(0, min(new_index, len(mylist)-1))

推荐答案

实际上,这很清楚.许多人很快学会了它.您可以使用评论来帮助他们.

This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.

new_index = max(0, min(new_index, len(mylist)-1))

这篇关于如何将整数钳位到某个范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆