Home > Net >  Python list comprehension to get max() of each list column
Python list comprehension to get max() of each list column

Time:07-05

I have following list of list:

lst = [[1,3], [3,4], [2,7], [6,5]]

How do I create "oneliner" to get list of max() of each "column"?

so for the example above the resulting list should be following: [6,7], where 6 is the maximum of "column 0" and 7 is the maximum of "column 1".

CodePudding user response:

You can use zip which splits the pairs into two separate tuples:

>>> lst = [[1,3], [3,4], [2,7], [6,5]]

>>> list(zip(*lst))
[(1, 3, 2, 6), (3, 4, 7, 5)]

So, overall:

>>> [max(v) for v in zip(*lst)]
[6, 7]

CodePudding user response:

If we assume not all "rows" will necessarily contain the same number of columns, despite the given example, we can get the minimum "column" bound with: min(map(len, lst)).

We can use this to iterate over the columns: for col_num in range(min(map(len, lst))).

And we can iterate over rows with for row in lst, so putting this together:

[[row[col_num] for row in lst] for col_num in range(min(map(len, lst)))]
# => [[1, 3, 2, 6], [3, 4, 7, 5]]

But we just need the maximum, and max can be fed a generator expression instead of a list to keep this a bit more memory-efficient, so:

[max(row[col_num] for row in lst) for col_num in range(min(map(len, lst)))]
# => [6, 7]
  • Related