class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        num1=num4=num5=num9=num10=num40=num50=num90=num100=num400=num500=num900=num1000=0
        
        
        for i in range(2):
            tmp = 0
            Length=len(s)
            for tmp in range(Length):
                if s[tmp:tmp+2]=='IV':
                    num4=num4+1
                    s = s[:tmp]+s[tmp+2:]
               
                elif s[tmp:tmp+2]=='IX':
                    num9=num9+1
                    s = s[:tmp]+s[tmp+2:]
                
                elif s[tmp:tmp+2]=='XL':
                    num40=num40+1
                    s = s[:tmp]+s[tmp+2:]
                
                elif s[tmp:tmp+2]=='XC':
                    num90=num90+1
                    s = s[:tmp]+s[tmp+2:]
                
                elif s[tmp:tmp+2]=='CD':
                    num400=num400+1
                    s = s[:tmp]+s[tmp+2:]
               
                elif s[tmp:tmp+2]=='CM':
                    num900=num900+1
                    s = s[:tmp]+s[tmp+2:]
                
                else:
                    s = s
    
                
        print(s)
        for i,num in enumerate(s):
            #print (i,num)
            if num == 'I':
                num1 = num1+1
            if num == 'V':
                num5 = num5+1
            if num == 'X':
                num10 = num10+1
            if num == 'L':
                num50 = num50+1
            if num == 'C':
                num100 = num100+1
            if num == 'D':
                num500 = num500+1
            if num == 'M':
                num1000 = num1000+1
        #print(num4,num9,num40,num90,num400,num900)       
        num = 1*num1+5*num5+10*num10+50*num50+100*num100+500*num500+1000*num1000+4*num4+9*num9+40*num40+90*num90+400*num400+900*num900
        return num

注意:

1 采用先判断特殊条件,之后再常规条件相加

2 enumerate函数用法

3 字符串切割与拼接

4 循环两次是因为两次才能覆盖所有情况,避免遗漏(通过测试了,具体原理需要研究)

附大佬代码:

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        a = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}        
        ans=0        
        for i in range(len(s)):            
            if i<len(s)-1 and a[s[i]]<a[s[i+1]]:                
                ans-=a[s[i]]
            else:
                ans+=a[s[i]]
        return ans