【问题标题】:How to get max value from a list of dictionaries? [duplicate]如何从字典列表中获取最大值? [复制]
【发布时间】:2022-02-26 05:30:39
【问题描述】:

我有如下的 python 字典列表。我想找到'high' 字段的最大值。

ohlc = [
  {
    'open' : 100,
    'high' : 105,
    'low' : 95,
    'close' : 103
  },
  {
    'open' : 102,
    'high' : 108,
    'low' : 101,
    'close' : 105
  }
  {
    'open' : 101,
    'high' : 106,
    'low' : 100,
    'close' : 105
  }
]

在这种情况下,函数应该返回 high = 108。

【问题讨论】:

  • 你尝试了什么?
  • 你做了什么尝试?与您的想法相反,StackOverflow 不是免费的编码服务。你应该做一个honest attempt at the solution

标签: python list


【解决方案1】:

我提供了一个简单易懂的使用for loop的方式,如下:

import sys
ohlc = [
    {
        'open': 100,
        'high': 105,
        'low': 95,
        'close': 103
    },
    {
        'open': 102,
        'high': 108,
        'low': 101,
        'close': 105
    },
    {
        'open': 101,
        'high': 106,
        'low': 100,
        'close': 105
    }
]

max_high = ohlc[0]['high'] to assign first high value.

for i in ohlc[1:]:
    if i['high'] > max_high:
        max_high = i['high']

print(max_high)
#108

【讨论】:

  • @joenpcnpcsolution 很乐意为您提供帮助。我更新了我的答案,为您提供更多信息。 :)
  • @martineau 感谢您的评论,我已按照您的指示修改了答案:)
【解决方案2】:

像这样使用 max 函数的 key 参数:

ohlc = [
  {
    'open' : 100,
    'high' : 105,
    'low' : 95,
    'close' : 103
  },
]
print(max(ohlc, key=(lambda item: item['high'])))

【讨论】:

  • FWIW,这也可以写成 max(ohlc, key=operator.itemgetter('high'))) 如果列表有,这可能比使用用户定义的 lambda 函数更快非常多的字典。
  • 很公平,关于 operator.itemgetter 的 TIL
猜你喜欢
  • 2022-10-05
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
相关资源
最近更新 更多