Skip to main content
 首页 » 编程设计

python之如何从列表中获取最大值

2025年05月04日19zdz8207

我希望从下面的字典中获得最高的“high”。

响应 =

 [   
       {   
          'timestamp':'2019-04-13T04:12:00.000Z', 
          'symbol':'XBTUSD', 
          'open':5065, 
          'high':5067, 
          'low':5065.5, 
          'close':5066.5, 
          'trades':13, 
          'volume':10002, 
          'vwap':5066.8829, 
          'lastSize':2, 
          'turnover':197408849, 
          'homeNotional':1.9740884899999998, 
          'foreignNotional':10002 
       }, 
       {   
          'timestamp':'2019-04-13T04:11:00.000Z', 
          'symbol':'XBTUSD', 
          'open':5065, 
          'high':5065, 
          'low':5065, 
          'close':5065, 
          'trades':0, 
          'volume':0, 
          'vwap':None, 
          'lastSize':None, 
          'turnover':0, 
          'homeNotional':0, 
          'foreignNotional':0 
       }, 
       {   
          'timestamp':'2019-04-13T04:10:00.000Z', 
          'symbol':'XBTUSD', 
          'open':5065, 
          'high':5065, 
          'low':5065, 
          'close':5065, 
          'trades':2, 
          'volume':2000, 
          'vwap':5065, 
          'lastSize':397, 
          'turnover':39486000, 
          'homeNotional':0.39486, 
          'foreignNotional':2000 
       } 
    ] 

然后打印所有“high”:

for h in response: 
   print (h['high']) 

打印:

<强> 5067 5065 5065

那么问题来了,如何从数字列表中获取最大值?在本例中为“5067”。我尝试过使用 max 方法,但无济于事。 (max(h['high'])) 不起作用。

请您参考如下方法:

使用itemgetter 和key 参数:

from operator import itemgetter 
 
max(h, key=itemgetter('high'))