I have a list like this:
alkaline_earth_values = [['beryllium', 4],
['magnesium', 12],
['calcium', 20],
['strontium', 38],
['barium', 56],
['radium', 88]]
If I simply use the max(list) method, it will return the answer 'strontium', which would be correct if I was trying to find the max name, however I’m trying to return the element whose integer is highest.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
max(alkaline_earth_values, key=lambda x: x[1])
The reason this works is because the key argument of the max function specifies a function that is called when max wants to know the value by which the maximum element will be searched. max will call that function for each element in the sequence. And lambda x: x[1] creates a small function which takes in a list and returns the first (counting starts from zero) element. So
k = lambda x: x[1]
is the same as saying
def k(l): return l[1]
but shorter and nice to use in situations like this.
Method 2
Use the key argument.
max(alk..., key=operator.itemgetter(1))
Method 3
it is rather tricky to assume that an item in a list is actually still a number. If the numbers have become strings, the max() will return the ‘value’ with the highest first number:
alkaline_earth_values = [['beryllium', '9'], ['magnesium', '12'],['calcium', '20'],
['strontium', '38'], ['barium', '56'], ['radium', '88']]
max(alkaline_earth_values, key=lambda x: x[1])
returns ['beryllium', '9']
max(alkaline_earth_values, key=lambda x: float(x[1]))
will do the trick, when you are sure it will be a number
Method 4
For high speed consider pandas or numpy:
Import pandas as pd
alkaline_earth_values = [['beryllium', 4], ['magnesium', 12],['calcium', 20],
['strontium', 38], ['barium', 56], ['radium', 88]]
pd.DataFrame(alkaline_earth_values)[1].max()
Method 5
You could convert your list of lists to a Counter and the call the .most_common() method. This easily allow you to find the maximum or top n values:
>>> from collections import Counter
>>> Counter(dict(alkaline_earth_values)).most_common(1)
[('radium', 88)]
>>> Counter(dict(alkaline_earth_values)).most_common(3)
[('radium', 88), ('barium', 56), ('strontium', 38)]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0