【问题标题】:How to find maximum value for a dictionary如何找到字典的最大值
【发布时间】:2017-09-24 11:05:39
【问题描述】:

假设我这里有一本字典:

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]}

列表中的每个值都来自特定的时间段。 (即 100 代表 AAPL 股票,100.03 代表 GOOGL 股票是第 1 期的价值,100.3 代表 AAPL 股票,150.22 代表 SSNLF 股票是第 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 是第二期的最高价。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案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,您可以指定任意数量的列:

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

    输出:

    [100.89, 200.11, 300, 500]
    

    【讨论】:

    • 喜欢这个答案!为什么你需要在yield max(list(zip(*stock_price.values()))[column]) 中转换为list(
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2022-08-14
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      相关资源
      最近更新 更多