简体   繁体   English

列表边界-最Python的方式是什么?

[英]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.

相关问题 在列表中循环直到特定值的最pythonic方式是什么? - What is the most pythonic way of looping in a list until a particular value? 忽略带有括号的列表中的单词的最有效(pythonic)方法是什么? - What is the most efficient (pythonic) way to ignore words in a list that has parantheses? 重构此列表构建代码的最Pythonic方法是什么? - What's the most Pythonic way to refactor this list building code? 从 OrderedDict 列表中查找项目的最pythonic 方法是什么? - what would be the most pythonic way of finding items from a list of OrderedDict? 什么是逻辑上结合布尔列表的最“pythonic”方式? - What is the most 'pythonic' way to logically combine a list of booleans? 从列表中弹出随机元素的最pythonic方法是什么? - What is the most pythonic way to pop a random element from a list? 在列表中找到与其他元素不同的元素的最pythonic方法是什么? - what is most pythonic way to find a element in a list that is different with other elements? 编写此筛选列表理解的最pythonic方法是什么? - What's the most pythonic way to write this filtered list comprehension? 识别列表中连续重复项的最 Pythonic 方法是什么? - What's the most Pythonic way to identify consecutive duplicates in a list? 用另一个反向扩展列表的最有效方法是什么? - What is the most pythonic way to extend a list with the reversal of another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM