Python3:
dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}
我有上面的字典,其值是列表中的列表。我想要做的是组合列表中相同的项目,并将整数添加到该值。
例如。因为丰田在那里3x然后将所有数字组合在一起给我另一个列表
[Toyota, 51]
最终结果应该是 不需要按此顺序
dct = {'Mazda': [['Ford', 95], ['Toyota', 51], ['Chrysler', 52]]}
答案 0 :(得分:3)
对于问题中的输入:
dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52],
['Toyota', 5], ['Toyota', 26]]}
试试这个:
from collections import defaultdict
for k, v in dct.items():
aux = defaultdict(int)
for car, num in v:
aux[car] += num
dct[k] = map(list, aux.items())
现在dct
包含预期结果:
dct
=> {'Mazda': [['Ford', 95], ['Toyota', 51], ['Chrysler', 52]]}
答案 1 :(得分:0)
存储两个列表:一个包含汽车名称,另一个包含数字。遍历字典中的列表,如果汽车尚未存在,则向每个列表添加新元素,或者将该数字添加到汽车索引。最后,zip()
将两个列表放在一起。
答案 2 :(得分:0)
dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}
newdct = {}
for item in dct:
newdct[item] = []
unqItems = {}
for val in dct[item]:
if val[0] not in unqItems:
unqItems[val[0]] = 0
unqItems[val[0]] += val[1]
for u in unqItems:
newdct[item].append([u, unqItems[u]])
print newdct
答案 3 :(得分:0)
使用itertools.groupby()
:
In [66]: dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}
In [67]: from itertools import groupby
In [68]: from operator import *
In [69]: dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}
In [70]: { x: [[k,sum(y[1] for y in g)] for k,g in groupby(sorted(dct[x]),
key=itemgetter(0))] for x in dct}
Out[70]: {'Mazda': [['Chrysler', 52], ['Ford', 95], ['Toyota', 51]]}