要列出整数分组的字符串

2024-09-27 00:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我需要 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]的行的范围。我们将非常感谢您的帮助。这件事我已经耽搁了好几个小时了。你知道吗


Tags: 函数inforifdef情况resulttemp
3条回答

我提出了一个更简洁的函数版本,它避免了使用字符串标记,这在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 

我不确定这是否是最好的解决方案,但在给定的情况下是有效的。你知道吗

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']

您正在迭代列表的所有组件,包括最后一项,然后测试下一项是否是运算符。这意味着当循环到达最后一个项时,就没有其他要测试的项,因此索引错误。你知道吗

请注意,运算符永远不会出现在表达式的末尾。也就是说,你不会得到像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

相关问题 更多 >

    热门问题