【问题标题】:Python numerical operations on dictionaries having tuple keys of strings and integers具有字符串和整数元组键的字典上的 Python 数值运算
【发布时间】:2020-06-20 07:43:13
【问题描述】:

这里的第一个问题,我对 Python 数据结构有点陌生。

在股票期权订单之后,我得到了这两个字典(示例):

price = {('GOOGL', 0): 45.75, ('GOOGL', 1): 45.57, ('TSLA', 0): 39.41, ('TSLA', 1): 39.31, ('TSLA', 2): 39.55, ('TSLA', 3): 39.39}
quantity = {('GOOGL', 0): 2.0, ('GOOGL', 1): 1.0, ('TSLA', 0): 1.0, ('TSLA', 1): 1.0, ('TSLA', 2): 4.0, ('TSLA', 3): 2.0}

第一个是每次执行的价格,第二个是每次执行的数量。

似乎找不到使用元组键访问价格和数量的方法,我想计算每个选项的平均价格以获得我可以访问的结构,例如:

average_price = {'GOOGL': 45.69, 'TSLA': 39.46}

步骤是什么?

谢谢!

【问题讨论】:

  • 请格式化代码。非常感谢你
  • 感谢 György 的建议,我简化为仅突出显示代码。问

标签: python-3.x string dictionary integer tuples


【解决方案1】:

此工作代码将向您展示如何处理价格字典:

price = {('GOOGL', 0): 45.75,
         ('GOOGL', 1): 45.57,
         ('TSLA', 0): 39.41,
         ('TSLA', 1): 39.31,
         ('TSLA', 2): 39.55,
         ('TSLA', 3): 39.39}

sum_dict = {}
avg_dict = {}

# Populate sum_dict with price sums, count, and calc avgs per ticker
for price_key, price_value in price.items():
    ticker = price_key[0]
    if not ticker in sum_dict.keys():
        sum_dict[ticker] = [0.0, 0, 0.0]
    sum_dict[ticker][0] += price_value
    sum_dict[ticker][1] += 1
    sum_dict[ticker][2] = sum_dict[ticker][0] / sum_dict[ticker][1]

# Tranfer avg data to avg_dict
for sum_key in sum_dict.keys():
    avg_dict[sum_key] = sum_dict[sum_key][2]
print('Per Ticker Price Avgs:', avg_dict)

如果您在完成数量字典的处理过程中需要进一步的帮助,请告诉我,但技术大致相同。

【讨论】:

  • 嗨斯科特!您没有使用数量字典来乘以价格:python quantity = {('GOOGL', 0): 2.0, ('GOOGL', 1): 1.0, ('TSLA', 0): 1.0, ('TSLA', 1): 1.0, ('TSLA', 2): 4.0, ('TSLA', 3): 2.0} 但是没关系,我得到了方法并且将能够实现它。非常感谢!问
  • QuantX,你是对的!我很抱歉 - 疏忽。我很高兴你能够吸收这项技术。如果您需要进一步的帮助来完成此操作,请告诉我...
猜你喜欢
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
相关资源
最近更新 更多