【问题标题】:How can I check if a list index exists?如何检查列表索引是否存在?
【发布时间】:2015-04-18 09:37:46
【问题描述】:

好像

if not mylist[1]:
    return False

没用。

【问题讨论】:

  • mylist[1] 会返回索引为 1 的元素。说这个元素是值False,你会怎么考虑?
  • 是的,我的代码很糟糕。如果可行的话,我尝试做的似乎是一种非常不合常规的方法。
  • 你从哪里得到1的值?

标签: python list


【解决方案1】:

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

if 0 <= index < len(list):

它实际上在内部被评估为

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

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

注意: Python 支持负索引。引用 Python documentation

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

这意味着每当你使用负索引时,该值将被添加到列表的长度并使用结果。所以,list[-1] 会给你元素list[-1 + len(list)]

所以,如果你想允许负索引,那么你可以简单地检查索引是否不超过列表的长度,像这样

if index < len(list):

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

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

当您尝试访问位于无效索引处的元素时,会引发 IndexError。所以,这个方法行得通。


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

if not mylist[1]:

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

【讨论】:

  • 如果负指数太低,你会得到一个超出范围的IndexError,所以如果你支持它,你可能需要检查index &gt;= -len(list)
  • 第一种方法的另一个缺点是 Python 允许通过 .insert 进行非顺序索引
  • @BrettG 实际上没有。如果在空列表上执行 lst.insert(3, 'c') 不会出现错误,但值 'c' 将插入下一个可用插槽(在本例中为索引 0)。至少对于 Python 3
【解决方案2】:

EAFP 风格的 Python:

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

【讨论】:

    【解决方案3】:

    如果是整数索引列表,我会这样做

    if 1 < len(mylist):
      ...
    

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

    if key in mydict:
      ...
    

    【讨论】:

      【解决方案4】:

      另一种(但速度稍慢)的方法:

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

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

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

      【讨论】:

        【解决方案5】:
        assert len(mylist) >= abs(index) + int(index >= 0), "Index out of range"
        

        assert len(mylist) > abs(index) - int(index < 0), "Index out of range"
        

        【讨论】:

          【解决方案6】:

          或者你可以这样做:

          if index in dict(enumerate(mylist)):
              return True
          

          虽然它的效率可能比range(len(mylist)) 还要低。也许有人应该为返回 PEP 中键范围的列表提出一个 keys() 方法。

          【讨论】:

            猜你喜欢
            • 2013-11-03
            • 1970-01-01
            • 2013-03-19
            • 2016-09-19
            • 2011-01-09
            • 2011-02-10
            • 2021-07-22
            • 2015-02-13
            • 2013-03-21
            相关资源
            最近更新 更多