我有以下代码:
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]
Run Code Online (Sandbox Code Playgroud)
基本上,我计算一个新索引并使用它来从列表中查找一些元素.为了确保索引在列表的边界内,我需要将这两个if语句写成4行.那是相当冗长,有点难看......我敢说,这是非常不科幻的.
还有其他更简单,更紧凑的解决方案吗?(和更多pythonic)
是的,我知道我可以if else在一行中使用,但它不可读:
new_index = 0 if new_index < 0 else len(mylist) - 1 if new_index >= len(mylist) else new_index
Run Code Online (Sandbox Code Playgroud)
我也知道我可以链max()和min()在一起.它更紧凑,但我觉得它有点模糊,如果我输错了就更难找到错误.换句话说,我觉得这很简单.
new_index = max(0, min(new_index, len(mylist)-1))
Run Code Online (Sandbox Code Playgroud)