2017-09-30 58 views
1

我創建了一個函數,該函數接受一個字符串並將其轉換爲一個字符串向量並返回此向量,但沒有空格和運算符分隔,但在創建時意識到變量i不會更新它們的值,過了一段時間,並重復插入,因爲我沒有更新? 觀測數據:這是不允許使用現有的方法,例如,斯普利特...字符串向量 - 變量更新

def vector(exp): 
    Exp = [] 
    for i in range(len(exp)):   
     if exp[i] != ' ' and exp[i] != '+': 
      j = i 
      while exp[i] != ' ' and exp[i] != '+' and i < len(exp):    
       i += 1 
      valor = exp[j:i] 
      Exp.append(valor)  
     elif exp[i] == '+': 
      Exp.append(exp[i])   
    return Exp 

exp = '3563 + 36+ 27' 
print(vector(exp)) 
+0

爲什麼不這樣做'exp.split(」「)'?它會返回'['3563','+','36','+','27']' –

+0

這是不允許的,這個想法是不使用現有的方法來處理字符串 –

+1

這是一個重要的細節你應該加入你的問題。 –

回答

2

一對夫婦的問題,因爲你已經發現,for循環和while循環並不總是與期望的混合影響。您可以通過在外循環中使用while循環來避免其中的一些問題。

同樣在你的inner while循環中,你需要向上移動i < len(exp)檢查。如果您不使用exp[i] != ' '將得到一個太大的i值進行評估,您將得到一個超出範圍錯誤的索引。

通過將i < len(exp)移到前面,這將失敗並防止評估其餘條件。

像這樣:

def vector(exp): 
    Exp = [] 
    i=1 
    while i < len(exp): 
     if exp[i] != ' ' and exp[i] != '+': 
      j = i 
      while i < len(exp) and exp[i] != ' ' and exp[i] != '+':    
       i += 1 
      valor = exp[j:i] 
      Exp.append(valor)  
     elif exp[i] == '+': 
      Exp.append(exp[i]) 
     i += 1 
    return Exp 

exp = '3563 + 36 + 27' 
print(vector(exp))