所以我的问题是编写一个function statement(),它将一系列浮点数作为输入,正数表示银行帐户的存款,负数表示从银行帐户中取款。您的函数应该返回两个浮点数的列表;第一个是存款的总和,第二个(负数)是取款的总和。在
我写的那个似乎是把取款空列表改为0,这样就不允许append函数工作了。我想知道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)
这些线条:
需要写为:
^{pr2}$否则,变量
withdrawals
和deposits
将反弹到sum
返回的整数对象。换句话说,它们将不再引用此处创建的列表对象:相关问题 更多 >
编程相关推荐