How can use the key
argument for the min
function to compare a list of objects's 1 attribute?
Example
class SpecialNumber: def __init__(self, i): self.number = i li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
You can also use the Python built-in min() function to get the min value in a list. The function returns the minimum value in the passed iterable (for example, list, tuple, etc.). Using the min() function is simple and is just a single line code compared to the previous example.
1. With Iterable Object. The min() function is widely used to find the smallest value present in an iterable like list, tuple, list of lists, list of tuples, etc. In the case of simple lists and tuples, it returns the smallest value present in the iterable.
Description. Python list method min() returns the elements from the list with minimum value.
http://docs.python.org/library/operator.html#operator.attrgetter
from operator import attrgetter min_num = min(li,key=attrgetter('number'))
Sample interactive session:
>>> li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)] >>> [i.number for i in li] [1, 3, 2] >>> min_num = min(li,key=attrgetter('number')) >>> print min_num.number 1
It's:
min(li, key=lambda x: x.number)
you need a function that accepts a SpecialNumber
and returns its element.
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