【问题标题】:Function to split the input expression into token units(python)将输入表达式拆分为标记单元的函数(python)
【发布时间】:2020-04-09 19:18:40
【问题描述】:
def get_token_list(expr):
    token_list_initial = expr.split(' ')
    token_list=[]
    for token in token_list_initial:
       if token in '+-/*^()':
          token_list.append(token)
       elif token == ' ':
          continue
       elif token in '0123456789':
          token=float(token)
          token=str(token)
          token_list.append(token)
    return token_list

运算符和操作数之间可能有空格。 运算符和操作数都必须作为列表中的字符串返回。 操作数必须是浮点数。

例如。

输入:1+2 *3/(4+5)

输出:['1.00', '+', '2.00', '*'......]

我不确定出了什么问题。如果您教我,我将不胜感激。

【问题讨论】:

  • 你能有多字符标记吗?如果不是,那么按字符迭代而不是尝试在空格上拆分更有意义。
  • 是什么让你觉得它错了?

标签: python python-3.x token postfix-operator infix-operator


【解决方案1】:

我尝试使用正则表达式来做,看看:

import re

input = "1+2 *3  (4+5)"
input = input.replace(' ','')

print([i for i in re.split('([^0-9])',input) if i != ''])

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 2017-04-30
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2014-11-02
    • 2021-05-17
    • 2021-05-21
    相关资源
    最近更新 更多