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



我正在使用列表,我正在尝试访问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/

最新更新