I have a list of lists and I should find the sublist whose second element has the max value.
I implemented it as follows, but I would say it's a bit 'suboptimal' :-)
def max_value(inputlist):
return max([sublist[-1] for sublist in inputlist])
and then
maxvalue = max_value(listofcounties)
for result in listofcounties:
if result[1] == maxvalue:
return result[0]
There's a way to accomplish that in a more coincise form?
Thank you very much for any hint! Bye Fabio
max
accepts an optional key
parameter; max
compares the return value of the key
function to determine which one is larger.
maxvalue = max(listofcounties, key=lambda x: x[-1])
>>> listofcounties = [['county1', 10], ['county2', 20], ['county3', 5]]
>>> max(listofcounties, key=lambda x: x[-1]) # by using `key`, max compares 10, 20, 5
['county2', 20]
Here is another option (though not a very efficient one):
Find all the sub-lists whose second element has the maximum value:
[n for n in listofcounties if n[1] == max([k[1] for k in listofcounties])]
Find the first sub-list whose second element has the maximum value:
[n for n in listofcounties if n[1] == max([k[1] for k in listofcounties])][0]
Split it into two statements in order to improve efficiency:
Find all the sub-lists whose second element has the maximum value:
maxvalue = max([k[1] for k in listofcounties])
[n for n in listofcounties if n[1] == maxvalue]
Find the first sub-list whose second element has the maximum value:
maxvalue = max([k[1] for k in listofcounties])
[n for n in listofcounties if n[1] == maxvalue][0]
Another simple approach using sorted
function:
# the exemplary list was borrowed from @falsetru answer
listofcounties = [['county1', 10], ['county2', 20], ['county3', 5]]
max_sequence = sorted(listofcounties, key=lambda l: l[1], reverse=True)[0]
print(max_sequence)
The output:
['county2', 20]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.