如何通过Python中的公式对字典值进行加权

时间:2021-03-13 20:25:15

I have a formula from dictionary. This is my formula:

我有一个字典公式。这是我的公式:

result = (1/1 * value1) + (1/2 * value2) + (1/3*value3) + ..N

This is my example dictionary:

这是我的示例字典:

StudentGrades = {0: [1, 2, 3, 4], 1: [5, 8, 10]} .

so it should return {0: 4, 1: 12.33}.

所以它应该返回{0:4,1:12.33}。

This is my code

这是我的代码

avgDict = {}
x = 1
for k,v in StudentGrades.items():
    avgDict[k] = float(sum(1 / x * v))
    x += 1

my actual code returns {0: 10.0, 1: 0.0}. So please can you solve this problem ?

我的实际代码返回{0:10.0,1:0.0}。那么请你能解决这个问题吗?

1 个解决方案

#1


0  

numpy provides a solution for this:

numpy为此提供了一个解决方案:

import numpy as np

StudentGrades = {0: [1, 2, 3, 4], 1: [5, 8, 10]}

Result = {k: np.dot(v, [1/i for i in range(1, len(v)+1)])\
             for k, v in StudentGrades.items()}

# {0: 4.0, 1: 12.333333333333332}

#1


0  

numpy provides a solution for this:

numpy为此提供了一个解决方案:

import numpy as np

StudentGrades = {0: [1, 2, 3, 4], 1: [5, 8, 10]}

Result = {k: np.dot(v, [1/i for i in range(1, len(v)+1)])\
             for k, v in StudentGrades.items()}

# {0: 4.0, 1: 12.333333333333332}