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?
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?
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.
>>> 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)
With Python 2.x you can do it like this:
alist = [(1,6),(2,5),(2,4),(7,5)]
temp = map(sorted, map(list, zip(*alist)))
min_x, max_x, min_y, max_y = temp[0][0], temp[0][-1], temp[1][0], temp[1][-1]
For Python 3, I think you'd only have change one line:
temp = list( map(sorted, map(list, zip(*alist))) )