【问题标题】:How to combine values of int's with the same group in list of tuples?如何将 int 的值与元组列表中的同一组组合?
【发布时间】:2020-10-03 08:41:34
【问题描述】:

我有一个如下所示的数据列表结构:

[('a', 1),('a', 2),('b', 0),('b', 1),('c', 0)]

如果第一项相同,我正在尝试组合元组的第二个值。 (并删除重复项)

最终结果应该是:

[('a', 3),('b', 1),('c', 0)]

我的方法是创建第二个空列表并检查列表中是否存在第一个元素,如果不存在则追加。否则循环遍历第二个列表并将迭代中的 [1] 项的值从第一个列表添加到第二个列表中的 [1] 项。我无法让我的概念发挥作用。如果有人有更有效的解决方案,我也愿意提出建议。

secondList = []
for item in firstList:
    if (secondList.count(item[0]]):
      secondList.append(item)
    else:
      for item_j in secondList:
        if (item_j[0] == item[0]):
          item_j[1] = item_j[1]+item[1]

【问题讨论】:

    标签: python python-3.x list algorithm tuples


    【解决方案1】:

    您可以使用字典来获得所需的结果,而无需导入任何额外的模块:

    lst = [('a', 1),('a', 2),('b', 0),('b', 1),('c', 0)]
    
    Dict = {}
    
    for tup in lst:
    
        first=tup[0]
        second=tup[1]
        if first not in Dict:
            Dict[first]=0
        Dict[first]+=second
    
    secondList = []
    
    for key in Dict.keys():
        secondList.append((key,Dict[key]))
    
    print(secondList)
    

    【讨论】:

    • 正是我想要的,非常感谢@Kazi。
    【解决方案2】:

    将熊猫导入为 pd

    数据 = [("a", 1),("a", 2),("b", 0),("b", 1),("c", 0)]

    df = pd.DataFrame(data, columns=['c1','c2'])

    x = tuple (df.groupby('c1').sum().to_dict()['c2'].items())

    打印 (x)

    【讨论】:

      【解决方案3】:

      您可以使用itertools.groupby。首先按第 0 个索引对它们进行分组,然后对每个组 sum 第一个索引处的值进行分组:

      from itertools import groupby
      from operator import itemgetter
      data = [("a", 1),("a", 2),("b", 0),("b", 1),("c", 0)]
      
      result = [(k, sum(item[1] for item in g)) for k, g in groupby(data, key=itemgetter(0))]
      print(result)
      

      输出:

      [('a', 3), ('b', 1), ('c', 0)]
      

      P.S.:请注意,如果您的列表尚未按照文档中的说明在第 0 个索引上排序,这将无法按预期工作:

      一般情况下,iterable 需要已经在同一个 key 函数上排序。

      【讨论】:

        【解决方案4】:

        现有的答案很好,这是您可以使用defaultdict 的另一种方法:

        from collections import defaultdict
        
        def sum_tuples(tuples):
            result = defaultdict(int)
            for i in tuples:
                result[i[0]] += i[1]
            return [(k, result[k]) for k in result.keys()]
        

        【讨论】:

          【解决方案5】:

          这对于字典来说似乎是一个很好的案例。使用列表,您必须搜索列表以找到您所指的项目,O(n)。用字典,搜索时间是O(1)。

          tuple_dict = {}
          for item in firstList:
            key,value = item
            if key in tuple_dict:
              tuple_dict[key]+=value
            else:
              tuple_dict[key]=value
          

          然后你可以根据需要将它转换回你的元组列表

          tuple_list = []
          for key,value in tuple_dict.items():
            tuple_list.append((key,value))
          

          【讨论】:

            猜你喜欢
            • 2019-05-25
            • 2018-08-24
            • 1970-01-01
            • 2023-04-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多