簡體   English   中英

如何在不超出范圍的情況下訪問下一個索引?

[英]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。

有關將羅馬數字轉換為小數的另一個示例,請查看: https : //www.geeksforgeeks.org/converting-roman-numerals-decimal-lying-1-3999/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM