2017-12-03 113 views
0

例如,我需要 listBuilder('24+3-65*2') 返回 ['24', '+', '3', '-', '65', '*', '2']字符串列出与整数分组

我们不允许使用自定义的导入函数。我必须在没有他们的情况下做这项工作。这是我迄今为止...

def listBuilder(expr): 
    operators = ['+', '-', '*', '/', '^'] 
    result = [] 
    temp = [] 
    for i in range(len(expr)): 
     if expr[i] in operators: 
      result.append(expr[i]) 
     elif isNumber(expr[i]): #isNumber() returns true if the string can convert to float 
      temp += expr[i] 
      if expr[i+1] in operators: 
       tempTwo = ''.join(temp) 
       result.append(tempTwo) 
       temp = [] 
       tempTwo = [] 
      elif expr[i+1] == None: 
       break 
      else: 
       continue 

    return result 

在这一点上,我得到一个错误,串索引超出范围包括expr[i+1]行。帮助将不胜感激。我一直坚持了几个小时。

+0

也许重复的问题https://stackoverflow.com/questions/47616114/how-to-loop-over-the-elementary-arithmetic-symbols – dkato

+0

你是如何处理的负数? – RoadRunner

回答

1

您正在遍历列表中的所有组件,包括最后一个项目,然后测试下一个项目是否为运算符。这意味着当你的循环到达最后一个项目时,没有更多项目要测试,因此索引错误。

请注意,运算符绝不会出现在表达式的末尾。也就是说,你不会得到像2+3-这样的东西,因为这没有意义。因此,您可以测试除最后一个之外的所有项目:

for idx, item in enumerate(expr): 
    if item in operators or (idx == len(expr)-1): 
     result.append(item) 
    elif idx != len(expr)-1: 
     temp += item 
     if expr[idx+1] in operators: 
      tempTwo = ''.join(temp) 
      result.append(tempTwo) 
      temp = [] 
      tempTwo = [] 
     elif expr[idx+1] == None: 
      break 
     else: 
      continue 
0

我不确定这是否是最佳解决方案,但适用于特定情况。

operators = ['+', '-', '*', '/', '^'] 
s = '24+3-65*2/25' 

result = [] 
temp = '' 

for c in s: 
    if c.isdigit(): 
     temp += c 
    else: 
     result.append(temp) 
     result.append(c) 
     temp = '' 
# append the last operand to the result list 
result.append(temp) 

print result 


# Output: ['24', '+', '3', '-', '65', '*', '2', '/', '25'] 
0

我想出了一个更简洁的函数版本,避免使用字符串标记,这在Python中更快。

您的代码抛出了索引错误,因为在上一次迭代中,您正在检查位置i + 1处的某个东西,这是位于列表末尾的一处。该生产线

if expression[i+1] in operators: 

,因为在最后的迭代i是最终名单索引,而检查不存在的列表项引发错误。

def list_builder(expression): 
    operators = ['+','-','*','/','^'] 
    temp_string = '' 
    results = [] 

    for item in expression: 
     if item in operators: 
      if temp_string: 
       results.append(temp_string) 
       temp_string = '' 
      results.append(item) 

     else: 
      if isNumber(item): 
       temp_string = ''.join([temp_string, item]) 

    results.append(temp_string) #Put the last token in results 

    return results