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
How can I check if a list index exists?
提问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 0
and 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
i
orj
is negative, the index is relative to the end of the string:len(s) + i
orlen(s) + j
is substituted. But note that -0 is still 0.
如果
i
或j
为负数,则索引相对于字符串的结尾: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 IndexError
is raised. So, this method works.
当您尝试访问无效索引处的元素时,IndexError
会引发an 。所以,这个方法有效。
Note:The method you mentioned in the question has a problem.
注意:你在问题中提到的方法有问题。
if not mylist[1]:
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.
让我们说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
回答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