【发布时间】: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