【问题标题】:How to scan a list with sublists of two elements and check for same element[0] and the summarize element[1] and create a final list with the result?如何扫描具有两个元素的子列表的列表并检查相同的元素 [0] 和汇总元素 [1] 并使用结果创建最终列表?
【发布时间】:2020-11-12 22:09:19
【问题描述】:

我有一个包含两个元素(“代码”和长度)子列表的列表,例如:

list = [['1', 12.0], ['5', 7.4], ['1', 5.0], ['4', 2.3], ['4', 1.0]]

我想扫描列表中具有相同“代码”的子列表元素,然后创建一个汇总长度的最终列表,如下所示:

final_list = [['1', 17.0], ['5', 7.4], ['4', 3.3]]

这样的字典也可以:final_dict = {'1': 17.0, '5': 7.4, '4': 3.3}

我该怎么做?非常感谢您的帮助!

【问题讨论】:

    标签: python list dictionary summarize


    【解决方案1】:

    使用collections.defaultdict

    例如:

    from collections import defaultdict
    
    lst = [['1', 12.0], ['5', 7.4], ['1', 5.0], ['4', 2.3], ['4', 1.0]]
    result = defaultdict(float)
    for k, v in lst:
        result[k] += v
    print(result)    #for normal dict use print(dict(result))
    

    输出:

    defaultdict(<class 'float'>, {'1': 17.0, '5': 7.4, '4': 3.3})
    

    【讨论】:

      【解决方案2】:

      你可以试试:

      correlation = {}
      sumlist = []
      for item in list:
          if item[0] in correlation.keys():
              correlation[item[0]] += item[1]
          else:
              correlation[item[0]] = item[1]
      
      for k, v in correlation.items():
          sumlist.append([k, v])
      

      这不需要模块。 Sumlist 就是结果。

      【讨论】:

        猜你喜欢
        • 2018-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-21
        • 1970-01-01
        • 1970-01-01
        • 2019-05-16
        相关资源
        最近更新 更多