Python 将数学表达式分解为一个部分列表,将数字与运算符分开

Python 将数学表达式分解为一个部分列表,将数字与运算符分开,python,Python,我试过: tokens = [t.strip() for t in re.split(r'((?:-?\d+)|[+\-*/()])', exp)] return [t for t in tokens if t != ''] 但它得到了错误的结果: Expected :[3, '+', -4, '*', 5] Actual :['3', '+', '-4', '*', '5'] 使用不带语法糖的for循环。使用字符串方法isdigit()将整数的str转换为int 例如: >

我试过:

tokens = [t.strip() for t in re.split(r'((?:-?\d+)|[+\-*/()])', exp)]  
return [t for t in tokens if t != '']
但它得到了错误的结果:

Expected :[3, '+', -4, '*', 5]

Actual   :['3', '+', '-4', '*', '5']

使用不带语法糖的for循环。使用字符串方法
isdigit()
将整数的str转换为int

例如:

>>> "4".isdigit()
>>> True

您需要在适当的地方将
列表中的项目强制转换为
int
s

def try_int(s):
    try:
        return int(s)
    except ValueError:
        return s
然后在函数中,可以将其应用于退货列表中的所有项目

return [try_int(t) for t in tokens if t != '']

请花一些时间阅读如何创建一个。
[int(t)for t in tokens if t.isdigit(),否则t]
@alfasin
isdigit
将失败负数@PatrickHaugh可能重复您是对的:
[int(t)for t in tokens if t.match(r'^-?\d+$,t)否则t]
尝试
'-4'.isdigit()