0

我正在尝试制作一个程序,该程序在输入时接受字典并在银行账户中输出净金额。

我尝试了以下代码,但输出错误,我无法弄清楚原因:

netAmount = 0
bankDict = {'D':300,'D':300,'W':200,'D':100}
operations = bankDict.keys()
amount = bankDict.values()
for i in range(len(operations)):
    if operations[i] == 'D': netAmount += amount[i]
    elif operations[i] == 'W': netAmount -= amount[i]
else: pass
print netAmount
# OUTPUT: -100

输入不一定是字典。

4

4 回答 4

2

字典不会为单个键存储两个不同的条目。因此,当您bankDict使用 key 创建多个条目时"D",它只存储最后一个:

In [149]: bankDict = {'D':300,'D':300,'W':200,'D':100}

In [150]: bankDict
Out[150]: {'D': 100, 'W': 200}

您可能希望交易成为一个列表:

In [166]: transactions = [{"type": "deposit", amount: 300}, {"type": "deposit", amount: 300}, {"type": "withdrawal", amount: 200}, {"type": "deposit", amount: 100}]

In [167]:for transaction in transactions:
            if(transaction["type"] == "deposit"):
                netAmount += transaction["amount"]
            elif(transaction["type"] == "withdrawal"):
                netAmount -+ transaction["amount"]

您甚至可以将事务从字典中提取到一个类中。

于 2014-07-18T23:07:13.053 回答
0

您仍然可以传入字典,只需将其更改为

bank_dict = {'D':[300, 300, 100],
             'W':[200]
            }

然后,您将使用给定键的每个值列表的总和来调整帐户余额。

于 2014-07-18T23:24:27.817 回答
0

我只记得我之前问过一个关于机器人位置的类似问题。以下代码现在可以工作:

netAmount = 0
operations = ['D','D','W','D']
amount = [300,300,200,100]
i = 0

while i < (len(operations)):
    if operations[i] == 'D': netAmount += amount[i]
    elif operations[i] == 'W': netAmount -= amount[i]
    else: pass
    i += 1
于 2014-07-18T23:10:53.523 回答
0

这个问题可以用不同的方式解决:

def calculate_net_amount(trans_list):
    net_amount = 0 
    for i in trans_list:
        if(i[0] == 'D'):
            net_amount = net_amount + int(i[2::])
        elif(i[0] == 'W'):
            net_amount = net_amount - int(i[2::])
    return net_amount

trans_list=["D:300","D:200","W:200","D:100"]
print(calculate_net_amount(trans_list))
于 2019-09-05T12:37:34.050 回答