字典键的平均值与值展示

2024-04-20 09:34:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本类似这样的字典:

{0.234 : 100, 0.345 : 120, 2.45: 200, 2.55 : 250}

对于我的问题,我必须取键的floor(),然后取相应值的平均值。你知道吗

{0 : 110, 2 : 225}

我该怎么办?我在想,可能会在列表中添加与键的下限值相同的值,然后取所有列表的平均值:

{ 0 : [100, 120], 2 : [200, 250]}

但我也不知道怎么做。你知道吗


Tags: 列表字典平均值floor限值取键
2条回答
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]]

d的输出:

{ 0 : [100, 120], 2 : [200, 250]}

然后:

for x in d:
    d[x] = sum(d[x]) // len(d[x])

d的输出:

{0 : 110, 2 : 225}

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)

相关问题 更多 >