2015-10-06 68 views
-1

我目前正在學習python,所以我提前爲我的代碼的混亂道歉。我的函數是爲了接受一個字符串並將字符串數字加在一起。即一個123的字符串參數將變成1 + 2 + 3並返回6. 我的問題是當我迭代我的列表 - python一直指示變量已被引用之前,任何值已被分配。但是,當我打印出正在計算的值時,它們是正確的。更令人困惑的是,當我返回他們時 - 他們是不正確的。我似乎無法弄清楚我要出錯的地方。誰能告訴我這個問題可能是什麼?Python函數中的數字字符串轉換

謝謝!

listy = [] 
global total 
#Convert number to a list then cycle through the list manually via elements  and add them all up 
def digit_sum(x): 
    number= [] 
    number.append(x) 
    print number 

    for i in range(len(number)): 
     result = str(number[i]) 
     print result 

     #Now it has been converted to a string so we should be able to 
     #read each number separately now and re-convert them to integers 
     for i in result: 
      listy.append(i) 
      print listy 
      #listy is printing [5,3,4] 

     for i in listy: 
      total += int(i) 
      return total 

print digit_sum(x) 
+0

有誰能告訴我爲什麼這是低票?我仍然對堆棧溢出感到陌生,所以這是否有這樣的投票理由?缺乏清晰度嗎? – azurekirby

+0

你有正確的概念,但可以通過使用其他內置功能來使其更清潔。 我注意到的一件事是你的'return'語句嵌套在最後一個for循環中。您需要取消縮進,以便每次循環迭代時都不會調用它。 – Flyer1

回答

0

我相信我已經弄清楚我的代碼出了什麼問題。由於我對Python還是一個新手,我提出了一些非常新手的錯誤,比如沒有意識到在本地函數之外聲明變量會導致解決方案不符合我的預期。

由於我的退貨放置不正確,以及我的函數外部實例化了我的listy []變量,而不是讀取每個數字一次,它會讀取三次。

這現在已經在下面的代碼中得到糾正。

#Convert number to a list then cycle through the list manually via elements and add them all up 
def digit_sum(x): 
    total = 0 
    number= [] 
    number.append(x) 
    print number 

    for i in range(len(number)): 
     result = str(number[i]) 
     print result 

     #Now it has been converted to a string so we should be able to 
     #read each number separately now and re-convert them to integers 

     for i in result: 
      listy = [] 
      listy.append(i) 
      # print listy 
      #listy is printing [5,3,4] 

      for i in listy: 
       print i 
       total+= int(i) 
       print total 
       break 

    return total 

print digit_sum(111) 
3

我真的不知道發生了什麼事情在你的代碼存在,尤其是與搞砸縮進,但是你的問題很容易sovled:

sum(map(int, str(534))) 

它使一個字符串的數字,然後將每個數字轉換爲intmap,然後將其總和。

+0

我現在還在學習Python - 我對縮進道歉。我現在要修復它。 但534只是測試函數 - 它可以是任何數字字符串參數。 – azurekirby

+0

嗨馬爾蒂森,感謝您的方法。你覺得我的代碼混淆了什麼? – azurekirby

0

如果您關注的是隻有總結了一串號碼,然後列出理解本身會做或@Maltysen建議你可以使用地圖

sum([int(x) for x in "534"]) 
0

很簡單: 可以使用地圖或列表理解。他們幾乎相當。其他人使用地圖給出了答案,但我決定使用列表理解。

s = "1234567" 
sum([int(character) for character in s]) 
0

無視此答案,不應該在這裏發佈它。