Python制作词典中的平均值列表:所有平均值都相同



我有一本字典,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]]

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

即由于红鱼和一鱼是最低对的物种,我想找到红

鱼蓝鱼和一鱼蓝鱼之间的平均值,以及一鱼二鱼和一鱼蓝鱼之间的平均值。我有一段代码可以做到这一点:

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],这不是正确的答案,因为红鱼蓝鱼和一鱼蓝鱼的平均值,以及一鱼二鱼和红鱼二鱼之间的平均值应该是99.5。我做错了什么?

使用代码进行一些小计算,我能够得到[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 )

最新更新