0

I am trying to write a function that goes through a matrix (array of arrays) and deletes all rows that contain in them one specific value. As an example, my matrix looks for example like this:

a = [[[1,2,3], [1,3,2], [0,2], 0, True],
[[2,1,3], [1,3,2], [4,3], 2, False],
[[4,3,1], [9,2,1], [5,2], 1, True],
[[3,1,4], [5,2,1], [5,4], 2, False]]

I'd like to delete all rows that contain a False in the last column, so that I would end up with:

a = [[[1,2,3], [1,3,2], [0,2], 0, True],
[[4,3,1], [9,2,1], [5,2], 1, True]]

I tried amongst other things this:

def rmRows(a):
 for i in range(len(a)-1):
  if a[i][4] == False:
   a.remove(a[i])
 return a

but that doesn't seem to work. Any ideas on how to tackle that?

DK2AX
  • 265
  • 5
  • 16

2 Answers2

3

A simple List Comprehension would do the trick for you

>>> [elem for elem in a if elem[-1] == True]
[[[1, 2, 3], [1, 3, 2], [0, 2], 0, True], [[4, 3, 1], [9, 2, 1], [5, 2], 1, True]]

Now reflecting back to your code, the reason it is not working is because you are mutating the sequence while iterating. Every time you mutate the list, your iterator supposingly points to the next element there by skipping elements.

There are already few questions with some excellent answers in SO regarding this behavior.

Refer: Remove items from a list while iterating in Python

Refer: Python: removing items from inner and outer for loop iterators

Community
  • 1
  • 1
Abhijit
  • 62,056
  • 18
  • 131
  • 204
0

Instead of mutating the list try adding only when necessary, so take the compliment of your boolean expression and rewrite your function as so:

a = [[[1,2,3], [1,3,2], [0,2], 0, True], [[2,1,3], [1,3,2], [4,3], 2, False], [[4,3,1], [9,2,1], [5,2], 1, True], [[3,1,4], [5,2,1], [5,4], 2, False]]

def rmRows(a):
    b = []
    for row in a:
        if row[-1] == True:
            b.append(row)
    return b

print rmRows(a)

Gives:

[[[1, 2, 3], [1, 3, 2], [0, 2], 0, True], [[4, 3, 1], [9, 2, 1], [5, 2], 1, True]]
Dair
  • 15,910
  • 9
  • 62
  • 107
  • Thank you, that fixed it. I added an additional line a = b to rename the finished b array into a again. – DK2AX Nov 03 '14 at 19:48