2017-09-24 52 views
0

假設這裏有一本字典:我如何找到最大值的字典

stock_price = { 'AAPL' : [100,200,100.3,100.55,200.33], 
       'GOOGL': [100.03,200.11,230.33,100.20], 
       'SSNLF': [100.22,150.22,300,200,100.23], 
       'MSFT' : [100.89,200,100,500,200.11,600]} 

,並在名單上的每個值來自於一個特定時期。 (即AAPL股票爲100,GOOGL股票爲100.03,AAPL股票爲100.3,SSNLF股票爲150.22,期間2等)。

所以在這裏我創建了一個函數,它可以幫助我在特定的時間段找到最高的股票價格。

def maximum(periods): 
    """ 
    Determine the max stock price at a time of the day 

    Parameters 
    ---------- 
    times: a list of the times of the day we need to calculate max stock for 

    Returns 
    ---------- 
    A list 

result = [] 

#code here 

return result 

我的目標是輸入週期使得函數看起來最大([段])爲了找到最大的股票價格在那段時間。

預期結果的例子應該是這樣的:

最大([0,1])

[100.89,200.11]

這個節目100.89是所有股票中第一期的最高價格,200.11是最高價格在期間2中最高的價格。

回答

0

您可以使用dict.values迭代字典值。使用列表理解/生成器表達式獲取超出值的週期值;使用max以獲得最大的價值:

# 1st period (0) prices 
>>> [prices[0] for prices in stock_price.values()] 
[100, 100.03, 100.89, 100.22] 

# To get multiple periods prices 
>>> [[prices[0] for prices in stock_price.values()], 
    [prices[1] for prices in stock_price.values()]] 
[[100, 100.03, 100.89, 100.22], [200, 200.11, 200, 150.22]] 
>>> [[prices[0] for prices in stock_price.values()] for period in [0, 1]] 
[[100, 100.03, 100.89, 100.22], [100, 100.03, 100.89, 100.22]] 

>>> max([100, 100.03, 100.22, 100.89]) 
100.89 

>>> stock_price = { 'AAPL' : [100,200,100.3,100.55,200.33], 
...     'GOOGL': [100.03,200.11,230.33,100.20], 
...     'SSNLF': [100.22,150.22,300,200,100.23], 
...     'MSFT' : [100.89,200,100,500,200.11,600]} 
>>> 
>>> def maximum(periods): 
...  return [max(prices[period] for prices in stock_price.values()) 
...    for period in periods] 
... 
>>> maximum([0, 1]) 
[100.89, 200.11] 
1

我相信你正在尋找的東西是這樣的:

stock_price = { 'AAPL' : [100,200,100.3,100.55,200.33], 
      'GOOGL': [100.03,200.11,230.33,100.20], 
      'SSNLF': [100.22,150.22,300,200,100.23], 
      'MSFT' : [100.89,200,100,500,200.11,600]} 

def maximum(*args): 
    for column in args: 
     yield max(list(zip(*stock_price.values()))[column]) 
print(list(maximum(0, 1))) 

輸出:

[100.89, 200.11] 

通過使用*args,你可以指定爲人Y列,只要你想:

print(list(maximum(0, 1, 2, 3))) 

輸出:

[100.89, 200.11, 300, 500] 
+0

喜歡這個答案!爲什麼你需要轉入'list('in'yield max(list(zip(* stock_price.values()))[column])' – kaza