我有以下代码:
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]
基本上,我计算一个新的索引并使用它来从列表中查找某个元素。为了确保索引在列表的范围内,我需要将这两个if
语句写成四行代码。这显得有点啰嗦,有点丑陋... 我敢说,这相当不符合Python的编程风格。
是否有其他更简单、更紧凑的解决方案?(并且更符合Pythonic的编程风格)
是的,我知道可以在一行中使用if else
,但那样不易读:
new_index = 0 if new_index < 0 else len(mylist) - 1 if new_index >= len(mylist) else new_index
我也知道可以把max()
和min()
链接在一起。这样更加紧凑,但是我觉得有点晦涩难懂,如果我输入错误,很难找到错误。换句话说,我觉得这种方法不够直接。
new_index = max(0, min(new_index, len(mylist)-1))
请参见Pythonic way to replace list values with upper and lower bound (clamping, clipping, thresholding)?以获取处理NumPy数组中的值的特定技巧。