Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python min function with a list of objects

Tags:

python

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)] 
like image 500
Pwnna Avatar asked May 22 '11 01:05

Pwnna


People also ask

Can you use min on a list Python?

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.

Does the min function work in a list?

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.

What is min list in Python?

Description. Python list method min() returns the elements from the list with minimum value.


2 Answers

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 
like image 198
mechanical_meat Avatar answered Oct 21 '22 10:10

mechanical_meat


It's:

min(li, key=lambda x: x.number) 

you need a function that accepts a SpecialNumber and returns its element.

like image 40
viraptor Avatar answered Oct 21 '22 08:10

viraptor