简体   繁体   English

从具有多个元素的列表中返回最大值python

[英]return max value from a list that has multiple elements python

I have a list that has 2 elements in each tuple, one element being a string(fileid) and the other being a int(amount of words) 我有一个列表,其中每个元组中都有2个元素,一个元素是字符串(文件ID),另一个是int(字数)

('ca01', 715), ('ca02', 784), ('ca03', 690), ('ca04', 756), ('ca05', 625), ('ca06', 705)

I was wondering if there is a way to return both elements in the tuple based on the max value of the second element, for example here, the max value in this list is the second elements in the second tuple "784". 我想知道是否有一种方法可以基于第二个元素的最大值返回元组中的两个元素,例如,在此列表中的最大值是第二个元组“ 784”中的第二个元素。 However, I would like to return both elements "('ca02', 784)" 但是,我想返回两个元素“('ca02',784)”

You can use max() function witht a proper key: 您可以在没有适当键的情况下使用max()函数:

>>> lst = [('ca01', 715), ('ca02', 784), ('ca03', 690), ('ca04', 756), ('ca05', 625), ('ca06', 705)]
>>> 
>>> from operator import itemgetter
>>> 
>>> max(lst, key=itemgetter(1))
('ca02', 784)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM