我试图将算术运算列表添加到另一个空列表中并返回该列表

时间:2019-04-30 17:12:24

标签: python

我想通过拆分每个数字和运算符将算术运算符字符串添加到另一个列表中。当我附加3.1时,它变成3.0,然后是1.0。

我添加了浮动

def tokenization(expr):
    opr = ["+", "-", "*", "/", "^","(",")"]
    tokens = []
    for char in expr:       
        if char.isdigit():                  
            tokens.append(float(char)
        if char == '':
            continue
        if char in opr:
            tokens.append(char)
    return tokens

1 个答案:

答案 0 :(得分:1)

代码:

def tokenization(expr):
    opr = ["+", "-", "*", "/", "^", "(", ")"]
    tokens = []
    digit_readed, dot_readed, zero_readed = 0, 0, 0
    for idx, char in enumerate(expr):
        if char == " ":
            digit_readed, dot_readed, zero_readed = 0, 0, 0
        elif char in opr:
            tokens.append(char)
            digit_readed, dot_readed, zero_readed = 0, 0, 0
        else:
            if char.isdigit():
                digit_readed += 1
                if char == "0":
                    zero_readed += 1
                    if dot_readed > 0:
                        continue
            elif char == "." and digit_readed > 0:
                dot_readed += 1
                zero_readed, digit_readed = 0, 0
                continue
            else:
                raise ValueError("Unexpected '{}' on {} symbol".format(char, idx + 1))

            if dot_readed == 1:
                tmp = (str(round(tokens[-1])) + "." if digit_readed == zero_readed + 1 else str(tokens[-1])) + \
                       "0" * zero_readed
                tokens[-1] = float(tmp + char)
                zero_readed = 0
            elif digit_readed == 1:
                tokens.append(float(char))
            elif digit_readed > 1:
                tokens[-1] = float(str(round(tokens[-1])) + char)

    return tokens

print(tokenization("(3.1 + 6*2^2) * (2 - 1)"))

结果:

['(', 3.1, '+', 6.0, '*', 2.0, '^', 2.0, ')', '*', '(', 2.0, '-', 1.0, ')']