0

Let h be my matrix

h=[[0,346,34,6,7,0,0,34634,6,0],[2352,205230,523,50,5023,502,350,0,0]]

and I want to delete all the zeros from h.

So the result should be:

h=[[346,34,6,7,34634,6],[2352,205230,523,50,5023,502,350]]

I tried several different things from HERE and other questions but nothing seems to work for a matrix. Is there any nice solution to that?

Community
  • 1
  • 1
skrat
  • 648
  • 2
  • 10
  • 27

2 Answers2

2

You can simply use list comprehension:

h = [[element for element in row if element] for row in h]

So here we iterate over every row in h. For each row we construct a new list [element for element in row if element]. This means that for every element in that row, we check if it is equal to 0 (with if element). If it is not, bool(element) is True and thus we add element to that list. Otherwise we omit element.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

If you want to change the matrix in-place, you could do it with a function like the following. The trick is to go through the elements of each row backwards so that the indices of successive elements aren't changed because of ones being removed earlier.

def remove_zeros(matrix):
    for row in matrix:
        length = len(row)-1
        for i, elem in enumerate(reversed(row)):
            if not elem:  # zero value?
                row.pop(length-i)

h = [[0, 346, 34, 6, 7, 0, 0, 34634, 6, 0], [2352, 205230, 523, 50, 5023, 502, 350, 0, 0]]

remove_zeros(h)

print(h)  # -> [[346, 34, 6, 7, 34634, 6], [2352, 205230, 523, 50, 5023, 502, 350]]
martineau
  • 119,623
  • 25
  • 170
  • 301