Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful.
>>> import operator >>> >>> a_list = [('Tom', 23), ('Dick', 45), ('Harry', 33)] >>> sorted(a_list, key=operator.itemgetter(1), reverse=True)[0] ('Dick', 45)
I could do it quite verbosely...
>>> age = 0 >>> oldest = None >>> for person in a_list: ... if person[1] > age: ... age = person[1] ... oldest = person ... >>> oldest ('Dick', 45)
Use max() to Find Max Value in a List of Strings and Dictionaries. The function max() also provides support for a list of strings and dictionary data types in Python. The function max() will return the largest element, ordered by alphabet, for a list of strings. The letter Z is the largest value, and A is the smallest.
Definition and Usage. The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.
If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
max(a_list, key=operator.itemgetter(1))
You could use the max
function.
Help on built-in function max in module __builtin__:
max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
max_item = max(a_list, key=operator.itemgetter(1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With