如何检查列表索引是否存在? [英] How can I check if a list index exists?

查看:431
本文介绍了如何检查列表索引是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎好像

if not mylist[1]:
    return False

不起作用.

推荐答案

您只需检查所需的索引是否在0的范围内以及列表的长度之内,就像这样

You just have to check if the index you want is in the range of 0 and the length of the list, like this

if 0 <= index < len(list):

它在内部实际上被评估为

it is actually internally evaluated as

if (0 <= index) and (index < len(list)):

因此,该条件将检查索引是否在[0,列表长度]范围内.

So, that condition checks if the index is within the range [0, length of list).

注意:Python支持否定索引.引用Python 文档

Note: Python supports negative indexing. Quoting Python documentation,

如果ij为负,则索引相对于字符串的结尾:len(s) + ilen(s) + j被替换.但请注意,-0仍为0.

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.

这意味着每当您使用负索引时,该值将被添加到列表的长度中并使用结果.因此,list[-1]将为您提供元素list[-1 + len(list)].

It means that whenever you use negative indexing, the value will be added to the length of the list and the result will be used. So, list[-1] would be giving you the element list[-1 + len(list)].

因此,如果要允许使用负索引,则只需检查索引是否不超过列表的长度,就像这样

So, if you want to allow negative indexes, then you can simply check if the index doesn't exceed the length of the list, like this

if index < len(list):


另一种方法是这样,除了IndexError之外

a = []
try:
    a[0]
except IndexError:
    return False
return True

当您尝试访问无效索引处的元素时,会引发IndexError.因此,此方法有效.

When you are trying to access an element at an invalid index, an IndexError is raised. So, this method works.

注意:您在问题中提到的方法有问题.

Note: The method you mentioned in the question has a problem.

if not mylist[1]:

假设1mylist的有效索引,并且如果它返回

Lets say 1 is a valid index for mylist, and if it returns a Falsy value. Then not will negate it so the if condition would be evaluated to be Truthy. So, it will return False, even though an element actually present in the list.

这篇关于如何检查列表索引是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆