首页 > Python中list[]的定义到底是什么?

Python中list[]的定义到底是什么?

最近在尝试编一个编译器,但是在识别四则运算上出了问题,相关代码如下:


A的出处:

发现被减数o1每次都会“吃掉”o2,所以出现了错误,截图如下:

请问这是为什么,是否是因为代码中
部分导致o2的第一位被忽略?


你的代碼看得出來 Python 還沒熟練, 不過沒關係, 我們先從這個問題下手, 我稍微測試了一下你的 code:

def compute(exp):
    o1 = ''
    o2 = ''
    for c in exp:
        if c != '-':
            if not '-' in list(exp)[:list(exp).index(c)]:
                o1 = o1 + c
            else:
                o2 = o2 + c
    print(o1)
    print(o2)
    return int(o1)-int(o2)

if __name__ == '__main__':
    exp = input('-->')
    result = compute(exp)

結果:

-->1-1 
11

Traceback (most recent call last):
  File "x.py", line 16, in <module>
    result = compute(exp)
  File "x.py", line 12, in compute
    return int(o1)-int(o2)
ValueError: invalid literal for int() with base 10: ''

你發現了嗎? o1 跟 o2 收集的不對

先丟三個小提示:

  1. string 不必先轉成 list 才能問 in ( if b in A 就可以了)

  2. print(int(o1)-int(o2)) 應該要拿到外一層 (收集完畢才運算)

  3. lst.index(x) 總是返回 lst 中第一個 x 出現的位置


我回答過的問題: Python-QA

【热门文章】
【热门文章】