所以我的問題是編寫一個函數語句(),它將浮點數字列表作爲輸入,其中正數表示存款和負數表示從銀行賬戶。你的函數應該返回一個兩個浮點數的列表;第一個將是存款的總和,第二個(負數)將是提款的總和。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)
爲什麼您使用相同的名稱作爲不同的值? 'withdrawals = sum(withdrawals)'意味着您不再有任何方法可以引用曾經在'withdrawals'中的列表。只是不這樣做,你沒有問題:'total_withdrawals = sum(withdrawals)'。 – abarnert 2014-10-10 19:32:12