如何减少数组中的重复数据

时间:2019-02-03 18:06:00

标签: python-3.x

减少数据重复的最简单,最有效的方法是什么。

我试图制定一种算法,但是它开始变得复杂起来。

我确实将数据保存在这样的数组中:[[data, 'country_code',value],[data, 'country_code',value],[data, 'country_code',value],[data, 'country_code',value]]

例如,我有[[2019-01-23, "GER", 200],[2019-01-23,"USA",300],[2019-01-23,"GER", 301]]. 我需要:

[[2019-01-23,"GER", 501],[2019-01-23,"USA",300]]

2 个答案:

答案 0 :(得分:4)

使用defaultdict进行累积,并使用列表推导来收集结果:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for date, code, n in L:
...     d[date, code] += n
...     
>>> [[date, code, n] for [[date, code], n] in d.items()]
[['2019-01-23', 'GER', 501], ['2019-01-23', 'USA', 300]]

答案 1 :(得分:1)

最惯用的方法是使用Counter库中的collections

>>> from collections import Counter
>>> data = [
...     ['2019-01-23', 'GER', 200],
...     ['2019-01-23', 'USA', 300],
...     ['2019-01-23', 'GER', 301],
... ]
>>> counter = Counter()
>>> for date, country_code, count in data:
...     counter[(date, country_code)] += count
...
>>> counter
Counter({('2019-01-23', 'GER'): 501, ('2019-01-23', 'USA'): 300})
>>> output_data = [[date, country_code, count] for (date, country_code), count in counter.items()]
>>> output_data
[['2019-01-23', 'USA', 300], ['2019-01-23', 'GER', 501]]
相关问题