【问题标题】:sum one corresponding list element within python dictionary在python字典中求和一个对应的列表元素
【发布时间】:2017-05-28 17:09:39
【问题描述】:

我有一个任意数量的等长 python 字典的列表,其中包含匹配的列表键集,如下所示:

[{'Item 1':[5.25, 'Red', 'Large'], 'Item 2':[8.50, 'Blue', 'Small'], 'Item 3':[12.50, 'Tan', 'Medium']}, 
{'Item 1':[10.50, 'Red', 'Large'], 'Item 2':[14.25, 'Blue', 'Small'], 'Item 3':[17.25, 'Tan', 'Medium']}, 
{'Item 1':[12.25, 'Red', 'Large'], 'Item 2':[20.25, 'Blue', 'Small'], 'Item 3':[24.25, 'Tan', 'Medium']}]

每个产品的属性列表都是相同的,除了第一项是 int 或 float。

如何获得具有相同键集和相同值集的单个字典,但列表中的第一项被求和?也就是说,我想返回:

{'Item 1':[28.00, 'Red', 'Large'], 'Item 2':[43.00, 'Blue', 'Small'], 'Item 3':[54.00, 'Tan', 'Medium']}

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    如果输入如您所说,则以下工作:

    > lst = [
      {'Item 1':[5.25, 'Red', 'Large'], 'Item 2':[8.50, 'Blue', 'Small'], 'Item 3':[12.50, 'Tan', 'Medium']}, 
      {'Item 1':[10.50, 'Red', 'Large'], 'Item 2':[14.25, 'Blue', 'Small'], 'Item 3':[17.25, 'Tan', 'Medium']}, 
      {'Item 1':[12.25, 'Red', 'Large'], 'Item 2':[20.25, 'Blue', 'Small'], 'Item 3':[24.25, 'Tan', 'Medium']}
    ]
    
    > {k: [sum(d[k][0] for d in lst)] + lst[0][k][1:] for k in lst[0]}
    {
      'Item 3': [54.0, 'Tan', 'Medium'], 
      'Item 2': [43.0, 'Blue', 'Small'], 
      'Item 1': [28.0, 'Red', 'Large']
    }
    

    【讨论】:

      【解决方案2】:

      使用以下方法:

      result = {k: [sum(d[k][0] for d in price_list)] + v[1:] for k,v in price_list[0].items()}
      
      print(result)
      

      输出:

      {'Item 1': [28.0, 'Red', 'Large'], 'Item 3': [54.0, 'Tan', 'Medium'], 'Item 2': [43.0, 'Blue', 'Small']}
      

      【讨论】:

        猜你喜欢
        • 2013-10-28
        • 2021-09-04
        • 2018-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-08
        • 2019-06-01
        • 1970-01-01
        相关资源
        最近更新 更多