所以我的问题是编写一个函数语句(),它将浮点数列表作为输入,正数表示存款,负数表示来自银行账户的抽取。你的函数应该返回一个两个浮点数的列表;第一个是存款的总和,第二个(负数)将是提款的总和。
我写的那个似乎是将提取空列表更改为值0,因此不允许追加功能工作。我想知道python是否有这样的原因,或者它只是一个奇怪的错误?
以下是供参考的代码:
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)
答案 0 :(得分:3)
这些行:
withdrawals = sum(withdrawals)
deposits = sum(deposits)
final.append(deposits)
final.append(withdrawals)
需要写成:
final.append(sum(deposits))
final.append(sum(withdrawals))
否则,变量withdrawals
和deposits
将被反弹到sum
返回的整数对象。换句话说,它们将不再引用此处创建的列表对象:
deposits, withdrawals, final = [], [], []