使用for或while循环,如何提取最大值并打印出最大值键?
data = {
'Jeremy':73284,
'Hansel':8784.3,
'Uee':9480938.2,
'Seolhyun':984958.3,
'Ketsuno Ana':24131,
'Trump':45789
}
答案 0 :(得分:1)
>>> 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
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'
编辑
>>> 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