0

我有一个清单:

list = [(a,1),(b,2),(a,3)]

我想将它转换为一个字典,当有重复(例如(a,1)(a,3))时,它将获得平均值,因此字典将只有 1 个键:值对,在这种情况下是a:2

4

1 回答 1

3
from collections import defaultdict
l = [('a',1),('b',2),('a',3)]
d = defaultdict(list)
for pair in l:
    d[pair[0]].append(pair[1]) #add each number in to the list with under the correct key
for (k,v) in d.items():
    d[k] = sum(d[k])/len(d[k]) #re-assign the value associated with key k as the sum of the elements in the list divided by its length

所以

print(d)
>>> defaultdict(<type 'list'>, {'a': 2, 'b': 2})

甚至更好,最后生成一个普通的字典:

from collections import defaultdict
l = [('a',1),('b',2),('a',3)]
temp_d = defaultdict(list)
for pair in l:
    temp_d[pair[0]].append(pair[1])
#CHANGES HERE
final = dict((k,sum(v)/len(v)) for k,v in temp_d.items())
print(final)
>>> 
{'a': 2, 'b': 2}

请注意,如果您使用的是 2.x(如您所见,您需要调整以下内容以强制浮动除法):

(k,sum(v)/float(len(v)))

或者

sum(d[k])/float(len(d[k]))
于 2013-05-20T10:54:20.067 回答