python - 用python获取两个不同字典的平均分

标签 python python-3.x dictionary

我有一个 Python3 代码,它返回 2 个字典(两者都有相同的索引),第一个字典包含名称列表,第二个字典包含列表分数。

对于每个索引,列表可能包含重复的名称,也可能包含不同的名称,如下面的代码所示。

如何获取字典的每个索引、列表中每个人的平均值

我尝试在索引上进行嵌套 for 循环以提取每个索引上的列表

然后,我循环遍历名称列表中的每个项目,保存名称的索引,然后重新循环分数以获得平均值

names = {"0":['name1', 'name1', 'name2', 'name1'] , "1":['name1', 'name2', 'name2', 'name2', 'name2']}

scores = {"0":[0.5, 0.5, 1, 0.2], "1":[0.2, 0.8, 0.8, 0.9, 0.9]}

for ind in names:
    namelist = names[ind]
    scoreist = scores[ind]     #as ind in names is the same as in scores
.
.
.
    indices = list()
    counter = 0
    tempname = namelist[0]
    for name in names:
        if name == tempname:
            indices.append(counter)
        counter += 1

    total = 0
    for index in indicies:
    total += scorlist[index]

    average = total / scorelist

.
.
.

然后我弹出列表的索引并重新迭代。 我知道应该有一种更快、更干净的方法来做到这一点,而不是在 while 循环中嵌套 for 循环......

编辑:

输出应该类似于

{"0": [['name1',0.3], ['name2', 0.25]], "1":[['name1', 0.05], ['name2', 0.68]]}

最佳答案

我认为你需要:

res = {}
for k,v in names.items():
    merged = [[i,j] for i,j in zip(names[k],scores[k])]
    # [['name1', 0.5], ['name1', 0.5], ['name2', 1], ['name1', 0.2]]                                                                        
    # [['name1', 0.2], ['name2', 0.8], ['name2', 0.8], ['name2', 0.9], ['name2', 0.9]]   
    s = []
    for i in set(names[k]):
        temp = sum([x[1] for x in merged if x[0]==i])/len(names[k])
        s.append([i, temp])

    res[k] = s

print(res)

输出:

{'1': [['name1', 0.04], ['name2', 0.6799999999999999]], 
 '0': [['name1', 0.3], ['name2', 0.25]]} 

说明

  • 使用两个dict中的值合并创建一个二维列表
  • 找到唯一的名称并对其进行迭代以找到平均值。

关于python - 用python获取两个不同字典的平均分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55372450/

相关文章:

python - 按值过滤字典

python - 使用 operator.itemgetter() 作为排序键时,有没有办法转换值?

python - Pandas Groupby 应用函数来计算大于零的值

python - pyodbc.DataError : ('22018' , “[22018] [Microsoft][ODBC SQL Server 驱动程序][SQL Server]转换失败] 错误

python - IGraph 选择性能

python - PyGObject:无法控制进度条

python - 如何将 python dict 转换为标准形式的 geojson 文件?

javascript - 从 Javascript 获取 HTML 区域标签名称?

python - lambda 在此 python 代码中做了什么?

python - PIL.Image.verify() 破坏了将 PIL 图像转换为 Numpy 的能力