Reputation: 1354
I have a nested list like the following:
x = [[1, 5, 3, 4],
[5, 10, 7, 8],
[9, 9, 2, 12]]
I need to find to find the min and max values of the nested list transposed such that the result for min is:
1, 5, 2, 4 # 1 is the min of first column (1, 5, 9) a.s.o
and the max should be:
9, 10, 7, 12
I tried to convert it into a dataframe
first and then doing max and min on the different axis but all doesn't come up as the result I want.
Upvotes: 3
Views: 3345
Reputation: 92854
Simply with numpy
module:
import numpy as np
x = np.array([[1, 5, 3, 4], [5, 10, 7, 8], [9, 9, 2, 12]])
print(np.min(x, 0)) # [1 5 2 4]
print(np.max(x, 0)) # [ 9 10 7 12]
Upvotes: 1
Reputation: 12669
You can use list comprehension or other way:
print([min(item) for item in zip(*x)])
is same as:
min_list=[]
for i in zip(*x):
min_list.append(min(i))
print(min_list)
output:
[1, 5, 2, 4]
For max:
print([max(item) for item in zip(*x)])
is same as:
max_list=[]
for i in zip(*x):
max_list.append(max(i))
print(max_list)
output:
[9, 10, 7, 12]
Upvotes: 1
Reputation: 73450
You can do the following using the built-in map
, min
, max
functions and the zip(*...)
transpositioning pattern:
min_x = list(map(min, zip(*x)))
max_x = list(map(max, zip(*x)))
Or as pointed out by Chris_Rands, this shortened form will also work:
min_x = list(map(min, *x))
max_x = list(map(max, *x))
Or use comprehensions:
min_x = [min(col) for col in zip(*x)]
max_x = [max(col) for col in zip(*x)]
If you desperately want to do it one line:
min_x, max_x = zip(*[(min(col), max(col)) for col in zip(*x)])
Upvotes: 7