如何制作一个程序,输入字典并输出银行净额?
我正在尝试写一个程序,这个程序可以接收一个字典作为输入,然后输出银行账户的净金额。
我试过以下代码,但输出结果不对,我也搞不清楚为什么:
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 个回答
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))
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
0
你仍然可以传入一个字典,只需要把它改成
bank_dict = {'D':[300, 300, 100],
'W':[200]
}
然后你可以通过计算每个键对应的值列表的总和来调整账户余额。
2
字典不会为同一个键存储两个不同的条目。所以当你用多个条目创建 bankDict
,而这些条目的键都是 "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"]
你甚至可以把字典中的交易提取出来,放到一个单独的类里。