我有一个列表列表,我希望将它们合并以对index[1]
值匹配的内部index[0]
值求和。我的列表如下所示:
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]]
]
因此,我希望新结构为:
new_lists = [
['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]
我如何在Python中实现这一目标?
答案 0 :(得分:3)
您可以使用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)]
答案 1 :(得分:3)
或者,使用Counter
中的collections
。您可以通过递增每个键的值来手动初始化它:
from collections import Counter
c = Counter()
for i, j in lists:
c[i] += l[j]
或者,通过提供展开内容的平面列表,Counter
将为您进行计数:
c = Counter(sum([[i] * j[0] for i,j in lists], []))
在这两种情况下,使用列表理解来创建结果列表,使用c.items()
抓取计数器的内容:
r = [[i, j] for i, j in c.items()]
结果是:
print(r)
[['Supply', 8], ['Features', 5], ['Prints', 3],
['Gifts', 8], ['Accounts', 6], ['Politics', 9]]
答案 2 :(得分:1)
使用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)])