python从字典词典中取平均值列表:所有平均值相同

问题描述 投票:0回答:1

我有一个字典,d

d = {'redFish': {'redFish': 'inf', 'blueFish': 9, 'twoFish': 10, 'oneFish': 6},
'blueFish': {'redFish': 9, 'blueFish': 'inf', 'twoFish': 11, 'oneFish': 10},
'twoFish': {'redFish': 10, 'blueFish': 11, 'twoFish': 'inf', 'oneFish': 8},
'oneFish': {'redFish': 6, 'blueFish': 10, 'twoFish': 8, 'oneFish': 'inf'}}

我有一个查找并返回具有最低值的键-键-值对的函数:

lowestPair = ['name1', 'name2', float('inf')]
for name1 in d.keys():
    for name2 in d[name1].keys():
        if d[name1][name2] < lowestPair[2]:
            lowestPair = [name1, name2, d[name1][name2]]

我的最低一对作为一个群集,将被视为一个实体。我现在正在尝试浏览字典,并为每个物种找到值,这些值是我正在查看的物种与新集群中两个物种之间的平均值。

即因为redFish和oneFish是配对中最低的物种,所以我想找到redFish blueFish和oneFish Bluefish之间的平均值,以及oneFish twoFish和oneFish blueFish之间的平均值。

我有一段代码可以做到这一点:

averageList = []
for name in lowestPair[0:2]:
    for otherName in d[name].keys():
        if otherName not in lowestPair:
            average = (d[lowestPair[0]][otherName] + d[lowestPair[1]][otherName])/2
            nameDict[name][otherName] = average 
            averageList.append(average) 

但是,平均列表返回[9, 9, 9, 9],这不是正确的答案,因为redFish blueFish和oneFish Bluefish的平均值,并且oneFish twoFish和redFish twoFish之间的平均值应为99.5。我在做什么错?

python dictionary
1个回答
0
投票

使用该代码进行了几次较小的计算,我就得到了[9.5, 9.0, 9.75, 8.5]

[我所做的两个更改是我必须将字典d的输出转换为float(),然后将nameDict更改为d,因为在示例代码中未定义nameDict提供。这是下面的结果代码:

d = {'redFish': {'redFish': 'inf', 'blueFish': 9, 'twoFish': 10, 'oneFish': 6}, 'blueFish': {'redFish': 9, 'blueFish': 'inf', 'twoFish': 11, 'oneFish': 10}, 'twoFish': {'redFish': 10, 'blueFish': 11, 'twoFish': 'inf', 'oneFish': 8}, 'oneFish': {'redFish': 6, 'blueFish': 10, 'twoFish': 8, 'oneFish': 'inf'}}

lowestPair = ['name1', 'name2', float('inf')]
for name1 in d.keys():
    for name2 in d[name1].keys():
        if float( d[name1][name2] ) < lowestPair[2]:
            lowestPair = [name1, name2, d[name1][name2]]

averageList = []
for name in lowestPair[0:2]:
    for otherName in d[name].keys():
        if otherName not in lowestPair:
            average = (float( d[lowestPair[0]][otherName] ) + float( d[lowestPair[1]][otherName] ))/2
            d[name][otherName] = average 
            averageList.append(average) 

print( averageList )
© www.soinside.com 2019 - 2024. All rights reserved.