繁体   English   中英

如何找到字典的最大值

[英]How to find maximum value for a dictionary

假设我在这里有一本字典:

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为期间1的值,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

我的目标是输入时间段,以便函数看起来最大([periods]),以便找到该时间段的最大股票价格。

预期结果示例应如下所示:

最大值([0,1])

[100.89,200.11]

这表明100.89是所有股票中第1期的最高价格,而200.11是第2期中的最高价格。

我相信您正在寻找这样的东西:

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 ,您可以指定任意多个列:

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

输出:

[100.89, 200.11, 300, 500]

您可以使用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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM