将字典中某个键的值与同一字典中另一个键的值相乘

时间:2019-09-12 03:35:46

标签: python dictionary

计算股票X回报的平均值。以“平均返回:......”格式显示输出。数值结果包含三个小数位。

我尝试通过尝试使用循环来迈出第一步,但遇到了一个障碍。请帮助

"""Prediction of returns of Stock A and Stock B"""


    pred = {'scens': ['very pessimistic', 
                      'pessimistic', 
                      'baseline', 
                      'optimistic', 
                      'very optimistic'],                   # Scenarios of economic conditions 
            'probs': [0.15, 0.2, 0.3, 0.25, 0.1],           # Scenario probabilities
            'stock X': [0.02, 0.07, 0.13, 0.15, 0.18],      # Returns of stock X in each scneario
            'stock Y': [0.06, 0.11, 0.14, 0.19, 0.21]}      # Returns of stock Y in each scenario

2 个答案:

答案 0 :(得分:0)

从评论看来,您似乎正在寻找expected value。这可以通过一个简单的循环来计算:

def expected_value_stock_x(probabilities: List[float], stocks: List[float]) -> float:
    total = 0
    for prob, stock in zip(probabilities, stocks):
        total += prob * stock
    return total

要格式化结果,可以使用round(expected_value, 2)将结果修整到两位小数位。

答案 1 :(得分:0)

这样的东西适合你吗?

"""Prediction of returns of Stock A and Stock B"""


pred = {'scens': ['very pessimistic',
                  'pessimistic',
                  'baseline',
                  'optimistic',
                  'very optimistic'],                   # Scenarios of economic conditions
        'probs': [0.15, 0.2, 0.3, 0.25, 0.1],           # Scenario probabilities
        'stock X': [0.02, 0.07, 0.13, 0.15, 0.18],      # Returns of stock X in each scneario
        'stock Y': [0.06, 0.11, 0.14, 0.19, 0.21]}      # Returns of stock Y in each scenario

mean_return = 0
for index, returns in enumerate(pred['stock X']):
    mean_return += returns * pred['probs'][index]

print(round(mean_return, 2))

结果为0.1115,四舍五入为0.11

它应该很容易解释。我使用枚举同时具有内容和索引,因此,如果您还想访问循环中字典列表的其他元素,则可以轻松实现。