【问题标题】:sum in list of dictionaries python with exception字典列表 python 中的总和有例外
【发布时间】:2022-11-28 15:02:58
【问题描述】:

我如何从字典列表中获取金钱和支出的总和

金额=(蓝色和红色衬衫的金额)和(黄色和绿色衬衫的金额)

花费总和=(衬衫颜色蓝色和红色的花费总和)和(衬衫颜色黄色和绿色的花费总和)

我应该为衬衫颜色蓝色和红色制作新词典,为黄色和绿色制作另一个词典吗?

people = [{'name': 'A', 'shirtcolor':'blue', 'money':'100', spent:'50'}, {'name': 'B', 'shirtcolor':'red', 'money':'70', spent:'50'}, {'name': 'C', 'shirtcolor':'yellow', 'money':'100', spent:'70'}, {'name': 'D', 'shirtcolor':'blue', 'money':'200', spent:'110'},{'name': 'E', 'shirtcolor':'red', 'money':'130', spent:'50'}, {'name': 'F', 'shirtcolor':'yellow', 'money':'200', spent:'70'},{'name': 'G', 'shirtcolor':'green', 'money':'100', spent:'50'}]

预期输出:

Total Money:  500 and 400

Total spent: 260 and 190 

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    数据是

    people = [{'name': 'A', 'shirtcolor': 'blue', 'money': '100', 'spent': '50'},
              {'name': 'B', 'shirtcolor': 'red', 'money': '70', 'spent': '50'},
              {'name': 'C', 'shirtcolor': 'yellow', 'money': '100', 'spent': '70'},
              {'name': 'D', 'shirtcolor': 'blue', 'money': '200', 'spent': '110'},
              {'name': 'E', 'shirtcolor': 'red', 'money': '130', 'spent': '50'},
              {'name': 'F', 'shirtcolor': 'yellow', 'money': '200', 'spent': '70'},
              {'name': 'G', 'shirtcolor': 'green', 'money': '100', 'spent': '50'}]
    

    您只需要一个字典,其中颜色是键,值是一个键为“money”和“spent”的字典。然后你可以在那里添加所有条目。

    color_sum = dict()
    for entry in people:
        if entry['shirtcolor'] not in color_sum:
            color_sum[entry['shirtcolor']] = {'money':0, 'spent':0}
        color_sum[entry['shirtcolor']]['money'] += int(entry['money'])
        color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])
    

    使用 defaultdict 确实使这更容易。

    from collections import defaultdict
    
    color_sum = defaultdict(lambda: {'money':0, 'spent':0})
    for entry in people:
        color_sum[entry['shirtcolor']]['money'] += int(entry['money'])
        color_sum[entry['shirtcolor']]['spent'] += int(entry['spent'])
    

    color_sum 中的结果数据将是这样的:

    {'blue': {'money': 300, 'spent': 160}, 
     'red': {'money': 200, 'spent': 100}, 
     'yellow': {'money': 300, 'spent': 140}, 
     'green': {'money': 100, 'spent': 50}}
    

    现在您可以获得所需的信息。

    money_red_blue = color_sum["red"]["money"] + color_sum["blue"]["money"]
    money_yellow_green = color_sum["yellow"]["money"]+ color_sum["green"]["money"]
    print(f'Total money: {money_red_blue} and {money_yellow_green}')
    

    这将输出Total money: 500 and 400


    评论中的问题是如何从没有绿色和黄色之一的衬衫中获得所有的钱。在这种情况下,我们将不得不遍历字典中的聚合数据,并排除键为“green”和“yellow”的项目。

    money = 0
    for k, v in color_sum.items():
        if k not in {'green', 'yellow'}:
            money += v['money']
    print(money)
    

    或者作为 sum 和生成器的单行代码:

    money = sum(v['money'] for k, v in color_sum.items() if k not in {'green', 'yellow'})
    print(money)
    

    【讨论】:

    • 谢谢!我有另一个问题,因为我试图在 python 中探索更多,如果没有指定红色和蓝色怎么办(比如 Total money = (sum of not green or yellow) and (sum of green or yellow))?你上面的代码会有什么变化?
    • @leafscart 我将此添加到我的答案中。
    【解决方案2】:

    首先,您需要检查 spent 属性。它应该有这样的语法:'spent': 40。 所以人们会是这样的:

    people = [{'name': 'A', 'shirtcolor':'blue', 'money':'100', 'spent':'50'}, {'name': 'B', 'shirtcolor': 'red', 'money':'70', 'spent':'50'}, {'name': 'C', 'shirtcolor':'yellow', 'money':'100', 'spent': '70'}, {'name': 'D', 'shirtcolor':'blue', 'money':'200', 'spent':'110'}, {'name': 'E', 'shirtcolor ':'red', 'money':'130', 'spent':'50'}, {'name': 'F', 'shirtcolor':'yellow', 'money':'200', 'spent ':'70'},{'name': 'G', 'shirtcolor':'green', 'money':'100', 'spent':'50'}]

    然后您需要遍历列表并获取所有值。 您可以通过扩展此代码来做到这一点:

    money_blue = 0
    for i in range(len(people)):
        if people[i]['shirtcolor'] == "blue":
            money += int(people[i]['money'])
        
    
    print(money_blue)
    

    【讨论】:

      【解决方案3】:

      您可以尝试如下:

      product_list=[
          {"name": "A", "shirtcolor":"blue", "money":"100", "spent":"50"},
          {"name": "B", "shirtcolor":"red", "money":"70", "spent":"50"}, 
          {"name": "C", "shirtcolor":"yellow", "money":"100", "spent":"70"},
          {"name": "D", "shirtcolor":"blue", "money":"200", "spent":"110"},
          {"name": "E", "shirtcolor":"red", "money":"130", "spent":"50"},
          {"name": "F", "shirtcolor":"yellow", "money":"200", "spent":"70"},
          {"name": "G", "shirtcolor":"green", "money":"100", "spent":"50"}
      ]
      
      print(product_list)
      
      #sum of spent for blue and red
      blueSpent = sum([int(x["spent"]) for x in product_list if x["shirtcolor"]=="blue" or x["shirtcolor"]=="red"])
      print(blueSpent)
      
      #sum of spent for green and yellow
      greenSpent = sum([int(x["spent"]) for x in product_list if x["shirtcolor"]=="green" or x["shirtcolor"]=="yellow"])
      print(greenSpent)
      
      #sum of spent for blue and red
      blueMoney = sum([int(x["money"]) for x in product_list if x["shirtcolor"]=="blue" or x["shirtcolor"]=="red"])
      print(blueMoney)
      
      #sum of money for green and yellow
      greenMoney = sum([int(x["money"]) for x in product_list if x["shirtcolor"]=="green" or x["shirtcolor"]=="yellow"])
      print(greenMoney)
      

      【讨论】:

        猜你喜欢
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-24
        • 1970-01-01
        • 2023-01-11
        • 2021-02-08
        • 1970-01-01
        相关资源
        最近更新 更多