如何提取最高值并打印出最高值键?使用for或while循环

时间:2019-03-21 12:32:00

标签: python python-3.x

使用for或while循环,如何提取最大值并打印出最大值键?

data = {
    'Jeremy':73284, 
    'Hansel':8784.3, 
    'Uee':9480938.2, 
    'Seolhyun':984958.3, 
    'Ketsuno Ana':24131, 
    'Trump':45789
}

2 个答案:

答案 0 :(得分:1)

1。使用for或while循环(按要求)

>>> data = {'Jeremy': 73284, 'Hansel': 8784.3, 'Uee': 9480938.2, 'Seolhyun': 984958.3, 'Ketsuno Ana': 24131, 'Trump': 45789}
>>> 
>>> max_k = None
>>> max_v = None
>>> for k, v in data.items():
...     if max_v is None or v > max_v:
...         max_v = v
...         max_k = k
... 
>>> print(max_k)
Uee

2。使用max()

Python 2

>>> import operator
>>> data = {'Jeremy':73284, 'Hansel':8784.3, 'Uee':9480938.2, 'Seolhyun':984958.3, 'Ketsuno Ana':24131, 'Trump':45789}
>>> max(data.iteritems(), key=operator.itemgetter(1))[0]
'Uee'

Python 3

>>> import operator
>>> data = {'Jeremy':73284, 'Hansel':8784.3, 'Uee':9480938.2, 'Seolhyun':984958.3, 'Ketsuno Ana':24131, 'Trump':45789}
>>> max(data.items(), key=operator.itemgetter(1))[0]
'Uee'

编辑

使用max()更容易

>>> data = {'Jeremy': 73284, 'Hansel': 8784.3, 'Uee': 9480938.2, 'Seolhyun': 984958.3, 'Ketsuno Ana': 24131, 'Trump': 45789}
>>> max(data)
'Uee'

答案 1 :(得分:0)

您可以通过遍历各个键来找到最大值,同时在字典中保存最高值的键。最后,打印密钥及其相应的值。

这样的事情应该起作用。它在public class DevicesController : ApiController { [HttpPost] [ResponseType(typeof(IHttpActionResult))] [Route("api/v1/devices")] [ActionName("new_device")] [ValidateModel] public IHttpActionResult NewDevice([System.Web.Http.FromBody] Device device ) { ... } [HttpGet] [ResponseType(typeof(IHttpActionResult))] [Route("api/v1/devices")] [ActionName("devices_list")] [ValidateModel] public List<Device> GetAllDevices() { ... } 中有一个for循环。

python3