2017-09-24 51 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