Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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 在字典中计算键的下限和值的平均值_Python_List_Dictionary - Fatal编程技术网

Python 在字典中计算键的下限和值的平均值

Python 在字典中计算键的下限和值的平均值,python,list,dictionary,Python,List,Dictionary,我有一本字典,看起来像这样: {0.234 : 100, 0.345 : 120, 2.45: 200, 2.55 : 250} 对于我的问题,我必须以键为底,取相应值的平均值 {0 : 110, 2 : 225} 我该怎么做呢?我在想,可能会在列表中添加与键的下限值相同的值,然后取所有列表的平均值: { 0 : [100, 120], 2 : [200, 250]} 但我也不知道该怎么做 defaultdict用于基于公共密钥收集值,该密钥是原始dict中密钥的下限值 import ma

我有一本字典,看起来像这样:

{0.234 : 100, 0.345 : 120, 2.45: 200, 2.55 : 250}
对于我的问题,我必须以键为底,取相应值的平均值

{0 : 110, 2 : 225}
我该怎么做呢?我在想,可能会在列表中添加与键的下限值相同的值,然后取所有列表的平均值:

{ 0 : [100, 120], 2 : [200, 250]}
但我也不知道该怎么做

defaultdict用于基于公共密钥收集值,该密钥是原始dict中密钥的下限值

import math
from collections import defaultdict

original_dict = {0.234 : 100, 0.345 : 120, 2.45: 200, 2.55 : 250}
d = defaultdict(list)

for k,v in original_dict.iteritems(): # or .items() if you are on Python 3.x
     d[math.floor(k)].append(v)

for k,v in d.iteritems():
    d[k] = sum(v)/len(v)

print(d)
d的输出:

然后:

d的输出:


你不知道怎么做是什么意思?你试过什么?你读过与词典和列表相关的文档吗?家庭作业?我可能需要列表理解和/或字典理解。不过,如果这是家庭作业,我不想为你编写代码。“你不会那样学的。”约翰夏普。我在stackoverflow上看到了一些类似的问题,但它们是关于在列表中将键分组在一起的。我还没有看过字典和列表的文档。我现在正在做这件事,因为你建议我可能会找到一些有用的东西。@TomZych不,这不是家庭作业。这是一个学校项目,我有一本时间戳和频率字典。我正在尝试应用一个公式将midi文件的时间戳转换为刻度。学校项目……家庭作业……我看不出有什么不同。在任何情况下,你都应该阅读文档,并在这里发布之前尝试自己解决它。本网站提供特定问题的具体答案。这并不是为了无可奈何地举手,让别人为你做你的工作。注意:在python3.4+中,你应该使用而不是滚动一个自制的mean实现,它在大多数情况下都会失败。
import math
a = {0.234 : 100, 0.345 : 120, 2.45: 200, 2.55 : 250}
d = {}
for x in a:
    if (math.floor(x)) not in d:
        d[math.floor(x)] = [a[x]]
    else:
        d[math.floor(x)] += [a[x]]
{ 0 : [100, 120], 2 : [200, 250]}
for x in d:
    d[x] = sum(d[x]) // len(d[x])
{0 : 110, 2 : 225}