【问题标题】:How to merge list of tuples如何合并元组列表
【发布时间】:2019-01-17 02:27:15
【问题描述】:

我有两个这样的元组列表:

x1 = [('A', 3), ('B', 4), ('C', 5)]

x2 = [('B', 4), ('C', 5), ('D', 6)]

我想将两个列表合并为一个 x3 的新列表,以便添加列表中的值。

x3 = [('A', 3), ('B', 8), ('C', 10),('D',6)]

您能告诉我如何做到这一点吗?

【问题讨论】:

  • 使用collections.Counter。您只需直接添加 2 个实例。
  • 如果您将此作为练习,然后再讨论一下您尝试过的逻辑。否则,请使用 collections 包中的 Counter 对象。高性能,满足您的需求。

标签: python pandas list


【解决方案1】:

您可以创建一个字典,然后循环遍历每个列表中的值,然后为字典中的每个键添加当前值,或者如果当前不存在值,则将该值设置为等于当前值。之后您可以转换回一个列表。

例如:

full_dict = {}
for x in [x1, x2]:
    for key, value in x:
        full_dict[key] = full_dict.get(key, 0) + value # add to the current value, if none found then use 0 as current value

x3 = list(full_dict.items())

x3 的结果:

[('A', 3), ('B', 8), ('C', 10), ('D', 6)]

【讨论】:

    【解决方案2】:

    既然你标记了pandas

    df1,df2=pd.DataFrame(x1),pd.DataFrame(x2)
    pd.concat([df1,df2]).groupby(0,as_index=False).sum().apply(tuple,1).tolist()
    [('A', 3), ('B', 8), ('C', 10), ('D', 6)]
    

    【讨论】:

      【解决方案3】:

      使用collections.Counter

      >>> x1 = [('A', 3), ('B', 4), ('C', 5)]
      >>> x2 = [('B', 4), ('C', 5), ('D', 6)]
      >>> from collections import Counter
      >>> c1 = Counter(dict(x1))
      >>> c2 = Counter(dict(x2))
      >>> c3 = c1 + c2   
      >>> c3.items()
      dict_items([('A', 3), ('B', 8), ('C', 10), ('D', 6)])
      

      只需为每个列表创建一个Counter,您可以通过将元组列表转换为中间字典来做到这一点。然后只需添加计数器。

      要取回列表,只需调用计数器的 items 方法。从技术上讲,返回的是一个dict_items 对象,如果它真的很重要,它是一个list,那么只需调用c3.items() 上的列表,即list(c3.items())。

      使用 groupby 和 heapq.merge 的替代 1 班轮。

      from heapq import merge
      from itertools import groupby
      from operator import itemgetter
      
      x1 = [('A', 3), ('B', 4), ('C', 5)]
      x2 = [('B', 4), ('C', 5), ('D', 6)]
      
      result = [(a, sum(t[1] for t in b)) for a, b in groupby(merge(x1, x2), key=itemgetter(0))]
      print(result)
      

      heapq.merge 大致相当于sorted(itertools.chain(*iterables))。它基本上提供了一个排序的、合并的元组列表,可以提供给 groupby。

      【讨论】:

        【解决方案4】:

        我认为以下代码有效

        dict_x1=dict(x1)
        for item in x2:
          if item[0] in dictx1:
            dictx1[item[0]] += item[1]
          else:
            dictx1[item[0] = item[1]
        

        【讨论】:

          【解决方案5】:

          你也可以通过itertools解决这个问题

          from itertools import groupby
          from operator import itemgetter
          
          first = itemgetter(0)
          second = itemgetter(1)
          res = {}
          data = x1 + x2
          
          for _, g in groupby(sorted(data, key=first), key=first):
              group = list(g)
              k = first(first(group))
              v = sum(second(gr) for gr in group)
              res[k] = v
          
          print(sorted(res.items(), key=first))
          
          [('A', 3), ('B', 8), ('C', 10), ('D', 6)]
          

          【讨论】:

            猜你喜欢
            • 2012-10-15
            • 2011-01-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-19
            • 2021-11-11
            • 1970-01-01
            相关资源
            最近更新 更多