【问题标题】:building a dict of lists Python 3构建列表的字典 Python 3
【发布时间】:2017-03-19 00:14:12
【问题描述】:

我正在阅读一个 csv 文件,我必须构建一个列表字典,其中键是股票代码,值是该代码的收盘价列表。我无法按每只股票的最高和最低价格对代码进行排序。

预期的输出是:

>GOOG:  180.38 difference (672.93-492.55)
>LNKD:  100.82 difference (270.76-169.94)
>AAPL:  36.74 difference (133.0-96.26)
>FB:  25.76 difference (98.39-72.63)
>MSFT:  9.32 difference (49.61-40.29)

我的示例 csv 表文件:

>Ticker  Date       Open       High     Low     Close     Volume
>GOOG    25-Sep-15  629.77    629.77    611     611.97    2174009
>GOOG    24-Sep-15  616.64    627.32    612.4   625.8     2240098

我的代码没有产生预期的行为。我正在努力遍历字典中的键并按最大最小值对它们进行排序:

file_data = open('../python_data/stock_prices.csv').readlines()[1:]
stock_dict = {}

def price_diff(key):
    change_price = max(stock_dict[key]) - min(stock_dict[key])
    return (change_price)


for line in file_data:
    line = line.split(',')
    ticker = line[0]
    if ticker not in stock_dict:
        stock_dict[ticker] = []
    stock_dict[ticker].append(float(line[5]))

sorted_keys = sorted(stock_dict, key=price_diff, reverse=True)
#print(sorted_keys)

for key in stock_dict:
    print(key, round(max(stock_dict[key]) - min(stock_dict[key]),2))

【问题讨论】:

  • 你知道熊猫吗,pandas.pydata.org?您应该考虑使用 pandas 而不是自己解析 csv,除非您将其作为练习
  • 嗨 zyxue,感谢您的快速回复。我把它当作一个练习。
  • 你不应该排序字典,而不是sorted(stock_dict),试试sorted(stock_dict.items())

标签: python-3.x sorting dictionary


【解决方案1】:
sorted_items = sorted(stock_dict.items(), key=lambda (k, v): max(v) - min(v), reverse=True)

【讨论】:

    【解决方案2】:

    感谢@zyxue 的反馈。经过大量研究,我得出了这个结论,并得到了预期的输出。

    file_data = open('../python_data/stock_prices.csv').readlines()[1:]
    stock_dict = {}
    
    def price_diff(key):
        change_price = max(stock_dict[key]) - min(stock_dict[key])
        return (change_price)
    
    for line in file_data:
        line = line.split(',')
        ticker = line[0]
        if ticker not in stock_dict:
            stock_dict[ticker] = []
        stock_dict[ticker].append(float(line[5]))
    
    sorted_keys = sorted(stock_dict, key=price_diff, reverse=True)
    for key in sorted_keys:
        min_val = min(stock_dict[key])
        max_val = max(stock_dict[key])
        change_val = round(max(stock_dict[key]) - min(stock_dict[key]),2)
        print("{}: {} difference ({} - {})".format (key, change_val, max_val, min_val))
    

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2013-10-07
      • 2017-05-05
      • 2013-10-21
      相关资源
      最近更新 更多