Home > OS >  How to get a column-wise min of list of lists?
How to get a column-wise min of list of lists?

Time:12-27

I have a list of lists:

a = [[9, -2], 
     [8, 7], 
     [9, 100]]

I'm expecting the output of min(a) to be [8, -2].

But the actual output of min(a) is [8, 7]

Does anyone know why?

CodePudding user response:

min() finds the smallest element in the sequence. [8, -2] is not in the sequence, so that can't be the answer.

[8, 7] has the smallest first element, so it is the minimum.

CodePudding user response:

min(a) will give you the smallest row, performing a row by row comparison. You get [8,7] because [8,7] is smaller than [9,-2] and smaller than [9,100] (compared as whole lists).

If you want the minimum of each column independently, you can use zip to access column values and apply the min() function to each column:

[*map(min,zip(*a))]  # [8, -2]
  • Related