建立列表Python 3

时间:2017-03-19 00:14:12

标签: python-3.x sorting dictionary

我正在阅读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

我的代码没有产生预期的行为。我正在努力循环遍历dict中的键并按max-min值排序:

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))

2 个答案:

答案 0 :(得分:0)

sorted_items = sorted(stock_dict.items(), key=lambda (k, v): max(v) - min(v), reverse=True)

答案 1 :(得分:0)

感谢@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))