Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Find the min, max value in a list of tuples

alist = [(1,3),(2,5),(2,4),(7,5)] 

I need to get the min max value for each position in tuple.

Fox example: The exepected output of alist is

min_x = 1 max_x = 7  min_y = 3 max_y = 5 

Is there any easy way to do?

like image 545
user483144 Avatar asked Oct 23 '10 06:10

user483144


2 Answers

map(max, zip(*alist)) 

This first unzips your list, then finds the max for each tuple position

>>> alist = [(1,3),(2,5),(2,4),(7,5)] >>> zip(*alist) [(1, 2, 2, 7), (3, 5, 4, 5)] >>> map(max, zip(*alist)) [7, 5] >>> map(min, zip(*alist)) [1, 3] 

This will also work for tuples of any length in a list.

like image 193
cobbal Avatar answered Sep 23 '22 17:09

cobbal


>>> from operator import itemgetter >>> alist = [(1,3),(2,5),(2,4),(7,5)] >>> min(alist)[0], max(alist)[0] (1, 7) >>> min(alist, key=itemgetter(1))[1], max(alist, key=itemgetter(1))[1] (3, 5) 
like image 22
John La Rooy Avatar answered Sep 22 '22 17:09

John La Rooy