-2

Assume that I have a matrix:

a = [[4,7,2],[0,1,4],[4,5,6]] 

And I want to get

b = [0, 1]
c = [[2],[0,1]]
  • b = [0,1] because the inner lists of a at position 0 and 1 contain values that are smaller then 3.
  • c = [[2],[0,1]] because the [2] nd element of the first sublist in b is below 3 and [0,1] because the first and second element in the second sublist in b is below 3.

I tried :

for i in a:
   for o in i:
      if o < 3:
         print(i)

It only returns the original matrix.

How do I get b&c in python?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
wayne64001
  • 399
  • 1
  • 3
  • 13
  • 1
    "Matrix b is that a[0], a[1] have a value that is smaller than 3, c is a[0][2] and a[0][0], a[0][1] is less than 3". This doesn't make the question sound clear at all – Sheldore Jan 01 '19 at 16:04
  • This doesn't give it in the exact form you are looking for, but depending on why you want to do this, you might be interested in `np.where(a<3)` which outputs the tuple `([0,1,1],[2,0,1])` giving all the indices where `a<3`. – overfull hbox Jan 01 '19 at 17:00

1 Answers1

0

You can leverate enumerate(iterable[,startingvalue]) which gives you the index and the value of the thing you iterate over:

a = [[4,7,2],[0,1,4],[4,5,6]] 

thresh = 3
b = [] # collects indexes of inner lists with values smaller then thresh
c = [] # collects indexes in the inner lists that are smaller then thresh
for idx, inner_list in enumerate(a):
    if any(value < thresh for value in inner_list):
        b.append(idx)
        c.append([])
        for idx_2, value in enumerate(inner_list):
            if value < thresh:
                c[-1].append(idx_2)

print(a)
print(b)
print(c)

Output:

[[4, 7, 2], [0, 1, 4], [4, 5, 6]]
[0, 1]
[[2], [0, 1]]

Doku:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69