【问题标题】:How to make a program which takes a dict as input and outputs bank net amount?如何制作一个以字典为输入并输出银行净额的程序?
【发布时间】:2014-09-10 04:20:52
【问题描述】:

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

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

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

输入不一定是字典。

【问题讨论】:

  • 一个字典中不能有多个相同的键。
  • 当然是字典……好尴尬。

标签: python python-2.7 banking


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

      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"]
      

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

      【讨论】:

      • 感谢您提供的信息。这解释了为什么我得到错误的输出。所以我需要为这种类型的程序提供不同类型的输入。
      【解决方案4】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-02
        • 2015-08-31
        • 1970-01-01
        • 1970-01-01
        • 2011-08-28
        • 2018-05-29
        • 2014-10-30
        • 2019-02-28
        相关资源
        最近更新 更多