[英]List boundaries - what is the most Pythonic way?
I have a Python list and I want to check if a given index is out of bounds. 我有一个Python列表,我想检查给定索引是否超出范围。 Since I'm accepting user input I want to restrict the index to integers greater than or equal to 0. What is the most Pythonic way to do this? 由于我接受用户输入,因此我希望将索引限制为大于或等于0的整数。最Python化的方法是什么? Currently, this is my solution: 目前,这是我的解决方案:
def get_current_setting(self, slot):
if slot < 0 or slot > len(self.current_settings) - 1:
raise Exception("Error message...")
return self.current_settings[slot]
Why not just try and access the value, and you will get an IndexError
if it's out of bounds. 为什么不尝试访问该值,如果超出范围,您将得到一个IndexError
。 Any checks you want to do out of the ordinary, just do those beforehand manually. 您想做的任何检查都与众不同,只需事先手动进行。
def get_current_settings(self, slot):
if slot < 0:
raise IndexError(...)
return self.my_list[slot]
In Python, you can do both checks (lower and upper bound) at once, making the if-condition much more readable: 在Python中,您可以同时进行两项检查(下限和上限),使if条件的可读性更高:
def get_current_setting(self, slot):
if not 0 <= slot < len(self.current_settings):
raise Exception("Error message...")
return self.current_settings[slot]
我将用以下内容替换您的if行:
if slot not in range(len(self.my_list)):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.