从数组中删除重复项并添加值

2024-04-25 05:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组,由两列组成。第一列是类别,第二列是值。例如下面的一个:

[category1, 12], [category2, 78], [category3, 8], [category2, 53], [category4, 894] 

我试图创建一个数组,其中每个类别只出现一次,并且每个类别的所有值相加。你知道吗

我该怎么开始呢?你知道吗


Tags: 数组类别category2category1category4category3
3条回答

你可以用熊猫图书馆来整理清单

import pandas as pd

x = [['category1', 12], ['category2', 78], ['category3', 8], ['category2', 53], ['category4', 894]]
x = pd.DataFrame(x).pivot_table(index=[0], aggfunc='sum').reset_index().values.tolist()

使用这种技术是很有帮助的,因为aggfunc对于其他应用程序来说更棒!:D个

O/p公司

[['category1', 12], ['category2', 131], ['category3', 8], ['category4', 894]]

如果你想用列表和迭代来完成,你可以从

lst = [['category1', 12], ['category2', 78], ['category3', 8], ['category2', 53], ['category4', 894]]

tmp = []
for item in lst:
  if item[0] in [i[0] for i in tmp]:    # to check if ithis category is already present in the new list 
    for itm in tmp:      # if yes, locate it and add the integer value
      if itm[0] == item[0]:
        itm[1] += item[1]
  else:     # if not, simply append that item to new list
    tmp.append(item)

print(tmp)

输出:

[['category1', 12], ['category2', 131], ['category3', 8], ['category4', 894]]

但我必须说,dict技术更直观,在较长列表中的性能更好。你知道吗

您可以创建一个defaultdict并使用列表中的值更新字典,如下所示:

from collections import defaultdict
l = [['category1', 12], ['category2', 78], ['category3', 8], 
     ['category2', 53], ['category4', 894]]

d = defaultdict(int)
for cat, i in l:
    d[cat] += i

print(d)
defaultdict(int,
            {'category1': 12,
             'category2': 131,
             'category3': 8,
             'category4': 894})

如果你想让它回到list

list(map(list, d.items()))
# [['category1', 12], ['category2', 131], ['category3', 8], ['category4', 894]]

相关问题 更多 >