Python将空列表更改为整数

2024-09-30 00:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的问题是编写一个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)

Tags: ofthetestarefinalstatement银行帐户sum
1条回答
网友
1楼 · 发布于 2024-09-30 00:31:43

这些线条:

withdrawals = sum(withdrawals)
deposits = sum(deposits)
final.append(deposits)
final.append(withdrawals)

需要写为:

^{pr2}$

否则,变量withdrawalsdeposits将反弹到sum返回的整数对象。换句话说,它们将不再引用此处创建的列表对象:

deposits, withdrawals, final = [], [], []

相关问题 更多 >

    热门问题