Reputation: 3848
Need to get the min and max values of each index in the sublists of a list.
If my list is [[1, 2], [4, 1], [2, 2], [1, 6], [5, 3]]
, I do the following:
xmin = min(i[0] for i in mylist)
ymin = min(i[1] for i in mylist)
xmax = max(i[0] for i in mylist)
ymax = max(i[1] for i in mylist)
# Results:
xmin = 1
xmax = 5
ymin = 1
ymax = 6
While very explicit in what I am doing with those 4 lines, is there a way to get it in tuple unpack?
Upvotes: 1
Views: 241
Reputation: 7867
for list of lists p
, we can transpose and unpack using
p1, p2 = zip(*p)
then find min and max as
max(p1)
min(p1)
max(p2)
min(p2)
Upvotes: 7
Reputation: 164623
For a generic solution, you should not dynamically name variables. Instead, you can use a dictionary. This will work for any list of lists where each sublist is of the same length.
L = [[1, 2], [4, 1], [2, 2], [1, 6], [5, 3]]
from operator import itemgetter
n = len(L[0])
d_min = {i: min(map(itemgetter(i), L)) for i in range(n)}
d_max = {i: max(map(itemgetter(i), L)) for i in range(n)}
print(d_min, d_max, sep='\n')
{0: 1, 1: 1}
{0: 5, 1: 6}
Upvotes: 1