Python将一个空列表更改为一个整数
问题描述:
所以我的问题是编写一个函数语句(),它将浮点数字列表作为输入,其中正数表示存款和负数表示从银行账户。你的函数应该返回一个两个浮点数的列表;第一个将是存款的总和,第二个(负数)将是提款的总和。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)
deposits = sum(deposits)
final.append(deposits)
final.append(withdrawals)
需要被写成:
final.append(sum(deposits))
final.append(sum(withdrawals))
否则,变量withdrawals
和deposits
将反弹到由sum
返回的整数对象。换句话说,他们将不再引用这里创建的列表对象:
deposits, withdrawals, final = [], [], []
为什么您使用相同的名称作为不同的值? 'withdrawals = sum(withdrawals)'意味着您不再有任何方法可以引用曾经在'withdrawals'中的列表。只是不这样做,你没有问题:'total_withdrawals = sum(withdrawals)'。 – abarnert 2014-10-10 19:32:12