2014-10-10 27 views
0

所以我的問題是編寫一個函數語句(),它將浮點數字列表作爲輸入,其中正數表示存款和負數表示從銀行賬戶。你的函數應該返回一個兩個浮點數的列表;第一個將是存款的總和,第二個(負數)將是提款的總和。Python將一個空列表更改爲一個整數

而我寫的似乎是將退出空列表更改爲值0,因此不允許附加功能工作。我想知道是否有一個原因蟒蛇這樣做,或者如果它只是一個奇怪的錯誤?

下面是引用代碼:

def statement(lst): 
"""returns a list of two numbers; the first is the sum of the 
    positive numbers (deposits) in list lst, and the second is 
    the sum of the negative numbers (withdrawals)""" 
deposits, withdrawals, final = [], [], [] 
for l in lst: 
    print(l) 
    if l < 0: 
     print('the withdrawals are ', withdrawals) # test 
     withdrawals.append(l) 
     print('the withdrawals are ', withdrawals) # test 
    else: 
     print('the deposits are', deposits) # test 
     deposits.append(l) 
     print('the deposits are', deposits) # test 
    withdrawals = sum(withdrawals) 
    deposits = sum(deposits) 
    final.append(deposits) 
    final.append(withdrawals) 
+1

爲什麼您使用相同的名稱作爲不同的值? 'withdrawals = sum(withdrawals)'意味着您不再有任何方法可以引用曾經在'withdrawals'中的列表。只是不這樣做,你沒有問題:'total_withdrawals = sum(withdrawals)'。 – abarnert 2014-10-10 19:32:12

回答

3

這些行:

withdrawals = sum(withdrawals) 
deposits = sum(deposits) 
final.append(deposits) 
final.append(withdrawals) 

需要被寫成:

final.append(sum(deposits)) 
final.append(sum(withdrawals)) 

否則,變量withdrawalsdeposits將反彈到由sum返回的整數對象。換句話說,他們將不再引用這裏創建的列表對象:

deposits, withdrawals, final = [], [], [] 
+0

這是因爲for循環在Python中沒有形成額外的範圍。 – dom0 2014-10-10 19:30:26

+0

或者只是不要以混淆的方式重複使用相同的名稱,並且這個問題不會出現在第一位... – abarnert 2014-10-10 19:31:28

+0

@abarnert - 同意。我沒有把它作爲一個解決方案,但是因爲這些額外的變量名是不必要的,所以'sum(存款)'和'sum(withdrawals)'可以很容易地內聯。在這種情況下,額外的變量只會是代碼混亂。 :) – iCodez 2014-10-10 19:33:43

相關問題