1

How can I find index of column with smallest sum of elements. I would like to find short solution which uses lambdas. For example for given matrix:

[[7, 2, 7, 2, 8],
 [2, 9, 4, 1, 7],
 [3, 8, 6, 2, 4],
 [2, 5, 2, 9, 1],
 [6, 6, 5, 4, 5]]

It should return 3. Because third column has smallest sum of elements.

1 Answer 1

1

With numpy, you can sum by columns and use the argmin() to find out the minimum sum index:

import numpy as np
np.array(lst).sum(axis = 0).argmin()
# 3

Or you can use list comprehension without using numpy package:

min(((i, sum(v)) for i, v in enumerate(zip(*lst))), key = lambda x: x[1])[0]
# 3
  • use zip(*lst) to transpose the list
  • enumerate to loop through columns (since it has been transposed)
  • for each column take the index, and sum of the column
  • calculate the minimum pair by the sum, which returns a tuple (index, minimum)
Sign up to request clarification or add additional context in comments.

2 Comments

Based on your sollution I've found even shorter sollution which uses straight Python: min(enumerate(map(sum,zip(*m))),key=lambda x:x[1])[0]
Not necessarily faster though since both approaches use only generators but surely a nicer and shorter one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.