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) 
+1

为什么您使用相同的名称作为不同的值? 'withdrawals = sum(withdrawals)'意味着您不再有任何方法可以引用曾经在'withdrawals'中的列表。只是不这样做,你没有问题:'total_withdrawals = sum(withdrawals)'。 – abarnert 2014-10-10 19:32:12

这些行:

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