2015-10-11 65 views
1

我面臨的問題是能夠採用像「((1 + 4))+(2-1) - 3」這樣的字符串,並將它在[((1+ 4)),(2-1),3]。這也適用於其他數量的括號。我試着用索引來做它,並且沒有運氣就算括號。這裏是我到目前爲止的一些代碼:關於嵌套圓括號的Python

final = [] 
while("(" in string): 
final.append(string[string.index("("):string.index(")")+1]) 
left = string[:string.index("(")] 
right = string[string.index(")")+1:] 
string = string.replace("+", ";") 
string = string.replace("-", ";") 
string = string.split(";") 
for item in string: 
    if item.strip() != "": 
    final.append(item) 
+0

爲什麼列表中包含'3'? –

+0

需要處理不嵌套在圓括號中的東西,因爲這是一個基本的和合理的數學表達式 –

+0

難道你不想要更像[1 + 4,2-1,3]的東西,完全擺脫括號? – Guillaume

回答

-1

您可能想要使用這個正則表達式。這個答案可能不是最優的,但看看如何使用re模塊:

>>> import re 
>>> regex = re.compile(r"\s+[\+\*\-\/]\s+") 
>>> s = "((1+4)) + (2-1) - 3" 
>>> for sub in regex.findall(s): 
...  s = s.replace(sub, " ") 
>>> s 
'((1+4)) (2-1) 3' 
>>> s.split() 
['((1+4))', '(2-1)', '3'] 

所以,我們編譯使用re.compile正則表達式,這樣,我們可以一次又一次地使用正則表達式,而不必每次編譯一次。然後我們使用findall找到滿足正則表達式的子字符串,然後我們取每個子字符串並使用字符串上的replace函數將其替換爲單個空格。然後我們使用split,默認分隔符設置爲" "來分割字符串。

編輯:因爲我完全忘了,你可以使用re.split,它可以一舉完成上述所有功能。

>>> s = "((1+4)) + (2-1) - 3" 
>>> regex.split(s) 
['((1+4))', '(2-1)', '3'] 

感謝@BurhanKhalid :)

+1

您可能想要與OP覈對他們是否基本上只想分割空白,但我感覺他們沒有。 – TigerhawkT3

+0

提示:'re.split' –

+0

@GamesBrainiac如果''格式爲''((1 + 4))+(2 - 1) - 3''? –

0

正則表達式(https://docs.python.org/2/library/re.html)爲您提供最短,可能最快的解決方案。但是,如果你喜歡一個解決方案,更容易閱讀和理解試試這個:

def split_expr(s): 
    l = [] 
    p =0 
    expr = '' 
    for c in s: 
     if c=='(': p+=1 
     if c==')': p-=1 
     if (p==0) and (c in '+-*/'): 
      l.append(expr) 
      expr = '' 
     else: 
      expr += c 
    else: 
     l.append(expr) 
    return l 

你也可以看到這個帖子(How to split but ignore separators in quoted strings, in python?)。它可以激發你一些更優雅的解決方案。