你只需要检查你想要的索引是否在0的范围和列表的长度,像这样
if 0 <= index < len(list):
实际上是内部评估
if (0 <= index) and (index < len(list)):
因此,该条件检查索引是否在[0,列表的长度]范围内.
注意:Python支持负数索引.引用Python documentation,
If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
这意味着每当使用负数索引时,该值将被添加到列表的长度,并将使用结果.所以,列表[-1]会给你元素列表[-1 len(list)].
所以,如果你想允许负的索引,那么你可以简单地检查索引是否不超过列表的长度,像这样
if index < len(list):
另一种方法是,除了IndexError,像这样
a = []
try:
a[0]
except IndexError:
return False
return True
当您尝试访问无效索引的元素时,会引发IndexError.所以这个方法有效.
注意:您在问题中提到的方法有问题.
if not mylist[1]:
让我们说1是mylist的有效索引,如果它返回一个Falsy value.然后不会否定它,所以if条件将被评估为Truthy.所以,它将返回False,即使一个元素实际存在于列表中.