3

Python3:

dct = {'Mazda': [['Ford', 95], ['Toyota', 20], ['Chrysler', 52], ['Toyota', 5], ['Toyota', 26]]}

我有上面的字典,其中的值是列表中的列表。我想做的是组合列表中相同的项目并将整数添加到该值。

例如。因为丰田在那里 3x 然后将所有数字组合在一起给我另一个列表

[Toyota, 51]

最终结果应该是不需要按这个顺序

dct = {'Mazda': [['Ford', 95], ['Toyota', 51], ['Chrysler', 52]]}
4

4 回答 4

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]]}
于 2012-11-29T21:35:11.590 回答
0

存储两个列表:一个包含汽车名称,一个包含数字。遍历字典中的列表,如果汽车不存在,则在每个列表中添加一个新元素,否则将数字添加到汽车索引中。最后,zip()这两个列表在一起。

于 2012-11-29T21:29:18.133 回答
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
于 2012-11-29T21:35:26.000 回答
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]]}
于 2012-11-29T21:36:26.537 回答