Python 如何检查列表索引是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29715501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:55:21  来源:igfitidea点击:

How can I check if a list index exists?

pythonlist

提问by Sundrah

Seems as though

好像

if not mylist[1]:
    return False

Doesn't work.

不起作用。

采纳答案by thefourtheye

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

你只需要检查你想要的索引是否0在列表的范围和长度内,就像这样

if 0 <= index < len(list):

it is actually internally evaluated as

它实际上在内部被评估为

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

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

因此,该条件检查索引是否在 [0, length of list) 范围内。

Note:Python supports negative indexing. Quoting Python documentation,

注意:Python 支持负索引。引用 Python文档

If ior jis negative, the index is relative to the end of the string: len(s) + ior len(s) + jis substituted. But note that -0 is still 0.

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

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)].

这意味着每当您使用负索引时,该值将被添加到列表的长度并使用结果。所以,list[-1]会给你元素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):


Another way to do this is, excepting IndexError, like this

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

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

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

当您尝试访问无效索引处的元素时,IndexError会引发an 。所以,这个方法有效。



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

注意:你在问题中提到的方法有问题。

if not mylist[1]:

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

让我们说1是一个有效的索引mylist,如果它返回一个Falsy 值。然后not将否定它,因此if条件将被评估为Truthy。因此,False即使列表中实际存在一个元素,它也会返回。

回答by csl

In the case of integer-indexed lists, I'd simply do

在整数索引列表的情况下,我只是做

if 1 < len(mylist):
  ...

For dicts, you can of course do

对于 dicts,你当然可以这样做

if key in mydict:
  ...

回答by Ben

In the EAFPstyle of Python:

在Python的EAFP风格中:

try:
    mylist[1]
except IndexError:
    print "Index doesn't exist!"

回答by Zlatko Karaka?

Alternative (but somewhat slower) way of doing it:

替代(但有点慢)的做法:

if index not in range(len(myList)):
    return False

It gets a bit more verbose when accounting for negative indices:

在考虑负指数时,它会变得更加冗长:

if index not in range(-len(myList), len(myList)):
    return False