簡體   English   中英

列出整數分組的字符串

[英]String to list with integers grouped

例如,我需要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]的行的范圍。 幫助將不勝感激。 我已經堅持了幾個小時。

您正在遍歷列表的所有組件,包括最后一個項目,然后測試下一個項目是否是運算符。 這意味着當您的循環到達最后一項時,沒有其他項目可以測試,因此索引錯誤。

注意,運算符永遠不會出現在表達式的末尾。 也就是說,您不會得到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

我不確定這是否是最佳解決方案,但可以在給定的情況下使用。

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

我想出了一個更簡潔的函數版本,避免使用字符串索引,這在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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM