尝试访问最后一个索引时出现索引超出范围错误

Index out of range error when trying to access the last index

我正在做 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

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

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

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