Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将列表转换为dict并平均重复项的值_Python_Python 2.7_Dictionary - Fatal编程技术网

在python中将列表转换为dict并平均重复项的值

在python中将列表转换为dict并平均重复项的值,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我有一份清单: list = [(a,1),(b,2),(a,3)] 我想把它转换成一个dict,当有一个副本时(例如,(a,1)和(a,3)),它将得到平均值,这样dict将只有一个键:值对,在这种情况下,a:2 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 ea

我有一份清单:

list = [(a,1),(b,2),(a,3)]
我想把它转换成一个dict,当有一个副本时(例如,
(a,1)
(a,3)
),它将得到平均值,这样dict将只有一个键:值对,在这种情况下,
a:2

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
所以

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

所以

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


或者,只需在顶部添加来自未来导入部门的
。谢谢。我将尝试一下,因为实际的列表比我的示例3元素列表长很多。让您知道它是如何运行的,或者,只需在顶部添加来自_future _导入部门的
。谢谢。我将尝试一下,因为实际的列表比我的示例3元素列表长很多。让你知道进展如何
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}
(k,sum(v)/float(len(v)))
sum(d[k])/float(len(d[k]))