如何在不越界的情况下访问下一个索引?

How to access the next index without going out of bounds?

我正在处理列表,我正在尝试访问 if 语句中的下一个值,如下所示:if((lst[i+1] != 'V') or (lst[i+1] != 'X')):。但是正如您所看到的,这非常容易出错。它确实引起了 IndexError.

在不破坏列表大小的情况下调用列表中的下一项的最佳方法是什么?

基本上,这是一个要求将罗马数字转换为常规数字的 LeetCode 作业。这是我的完整代码:

class Solution:
    def romanToInt(self, s: str) -> int:
        lst = list(s)
        counter = 0

        for i in range(len(lst)):

            if(lst[i] == 'I'):
                if((lst[i+1] != 'V') or (lst[i+1] != 'X')):
                    counter += 1
                elif(lst[i+1] == 'V'):
                    counter += abs(1-5)
                elif(lst[i+1] == 'X'):
                    counter += abs(1-10)

            if(lst[i] == 'V'):
                if(lst[i-1] != 'I'):
                    counter += 5
                else:
                    counter += abs(1-5)

            if(lst[i] == 'X'):
                if((lst[i+1] != 'L') or (lst[i+1] != 'C')):
                    counter += 10
                elif(lst[i+1] == 'L'):
                    counter += abs(10-50)
                elif(lst[i+1] == 'C'):
                    counter += abs(10-100)

            if(lst[i] == 'L'):
                if(lst[i-1] != 'X'):
                    counter += 50
                else:
                    counter += abs(10-50)

            if(lst[i] == 'C'):
                if((lst[i+1] != 'D') or (lst[i+1] != 'M')):
                    counter += 100
                elif(lst[i+1] == 'D'):
                    counter += abs(100-500)
                elif(lst[i+1] == 'M'):
                    counter += abs(100-1000)

            if(lst[i] == 'D'):
                if(lst[i-1] != 'C'):
                    counter += 500
                else:
                    counter += abs(100-500)

            if(lst[i] == 'M'):
                if(lst[i-1] != 'C'):
                    counter += 1000
                else:
                    counter += abs(100-1000)


        return counter

我不需要任何深度帮助。我只是想知道如何遇到这个问题,因为我找不到与条件语句相关的任何内容。

在您的代码中,您需要替换 for 循环:

for i in range(len(lst))

for i in range(len(lst))

避免超出范围,因为您在循环中的 i+1 和 i-1 访问 lst lst。

有关将罗马数字转换为小数的另一个示例,请查看:https://www.geeksforgeeks.org/converting-roman-numerals-decimal-lying-1-3999/