【问题标题】:Index out of range error when trying to access the last index尝试访问最后一个索引时出现索引超出范围错误
【发布时间】:2020-01-14 22:48:48
【问题描述】:

我正在做 leetcode,我的代码给了我这个我无法理解的错误。我被要求反转整数,这很简单。这些是测试用例:

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

我认为我需要的只是 if 语句来检查输入的条件,所以这就是我所做的:

class Solution:
    def reverse(self, x: int) -> int:
        string = str(x)
        lst = list(string)

        lst.reverse()

        if((lst[0]) == '0'):
            lst.pop(0)

        if((lst[-1] == '-')):
            lst.pop(-1)
            lst.insert(0, '-')

        output = ''.join(lst)

        return output

但是if((lst[-1] == '-')): 这一行抛出了IndexError: list index out of range 错误。我所做的只是访问列表的最后一个元素。我没有尝试访问不存在的索引。

我唯一需要知道的是为什么会发生此错误。因为这是 leetcode,所以我想自己修复代码。

最终代码

class Solution:
    def reverse(self, x: int) -> int:
        lst = list(str(x))

        lst.reverse()

        if(x < 0):
            lst.pop(-1)
            lst.insert(0, '-')

        int_output = int(''.join(lst))

        if(int_output < (2**32)):
            return int_output
        else:
            return 0

【问题讨论】:

  • 先检查if lst:,看看列表是否不为空。或者两者都if lst and lst[-1] == '-':
  • 请输入触发该条件的输入。您可能在处理字符串 0 吗?

标签: python index-error


【解决方案1】:

如果lst 为空,则会发生此错误,因为任何索引都将超出范围。

如果 x 最初是 "0",那么 lst 将是 ["0"]。然后第一个if 语句将删除"0" 元素,所以现在它将是[],这是一个空列表,你会得到那个错误。

如果您正在使用7. Reverse Integer,您还有其他问题。它说结果应该是一个整数,但你返回一个字符串。您也只删除了第一个 0。如果输入是12000,您将返回"0021" 而不是21

【讨论】:

  • 所以在反转并替换 - 符号之后,我要做的就是将其转换回 int,对吗?这会处理前导零。
  • LeetCode 有一个错误,它不接受一些反转。如果您愿意,请检查我的最新代码。我给了你一个赞成票并接受了你的回答。如果您认为这是一个很好的问题,您介意给我一个赞成票吗?
  • 最后的范围检查应该是if -2**32 &lt;= int_output &lt; 2**32:
猜你喜欢
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多