[英]Sum list values where index 0 values match?
I have a list of lists and I want to merge them to sum the inner index[1]
values where the index[0]
values match. 我有一个列表列表,我想将它们合并以将
index[0]
值匹配的内部index[1]
值求和。 My list looks like this: 我的清单如下所示:
lists = [
['Gifts', [4]],
['Gifts', [4]],
['Politics', [3]],
['Supply', [4]],
['Supply', [4]],
['Prints', [1]],
['Prints', [1]],
['Prints', [1]],
['Politics', [3]],
['Politics', [3]],
['Accounts', [2]],
['Accounts', [2]],
['Accounts', [2]],
['Features', [3]],
['Features', [2]]
]
I would therefore like the new structure to be: 因此,我希望新结构为:
new_lists = [
['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]
How do I achieve this in Python? 如何在Python中实现?
You can use defaultdict(int)
from collections
module: 您可以从
collections
模块使用defaultdict(int)
:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for key, value in lists:
... d[key] += value[0]
...
>>> dict(d)
{'Gifts': 8, 'Prints': 3, 'Accounts': 6, 'Features': 5, 'Supply': 8, 'Politics': 9}
>>> list(d.items())
[('Prints', 3), ('Features', 5), ('Supply', 8), ('Gifts', 8), ('Accounts', 6), ('Politics', 9)]
Or, use a Counter
from collections
. 或者,使用来自
collections
的Counter
。 You can initialize it either manually by incrementing the values for every key: 您可以通过增加每个键的值来手动初始化它:
from collections import Counter
c = Counter()
for i, j in lists:
c[i] += l[j]
Or, by providing a flat list of the expanded contents, Counter
will then do the counting for you: 或者,通过提供扩展内容的平面列表,
Counter
然后将为您进行计数:
c = Counter(sum([[i] * j[0] for i,j in lists], []))
In both cases, create the result list by using a list comprehension grabbing the contents of the counter with c.items()
: 在这两种情况下,都使用列表理解通过
c.items()
获取计数器的内容来创建结果列表:
r = [[i, j] for i, j in c.items()]
Result being: 结果是:
print(r)
[['Supply', 8], ['Features', 5], ['Prints', 3],
['Gifts', 8], ['Accounts', 6], ['Politics', 9]]
Use a defaultdict
: 使用
defaultdict
:
In [52]: from collections import defaultdict
In [53]: d = defaultdict(int)
In [54]: for name, (val,) in lists:
....: d[name] += val
....:
In [55]: d.items()
Out[55]: dict_items([('Politics', 9), ('Supply', 8), ('Prints', 3), ('Features', 5), ('Gifts', 8), ('Accounts', 6)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.