Getting the index of an element in an array containing another element

So let's say I have this array:

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

and I want to get the index of an internal array containing 5, for example. So in this case, the returned index I want is 1.

I tried ind = array.index(5), but I fully understand why this does not work, since the value in brackets must exactly match the element of the array. Another way I did this is

counter = 0
for each in array:
  if 5 in each: break
  else: counter = counter + 1

and it worked well for what I want, but I wanted to check if there is a simpler and clearer way to do this. Thanks

+4
source share
9 answers

next(..). , 5 , StopIteration. , .

>>> your_list = [[1,2,3],[4,5,6],[7,8,9]]
>>> next(i for i, x in enumerate(your_list) if 5 in x)
1
+7

break s. :

for ind, inner_arr in enumerate(array):
    if 5 in inner_arr:
        return ind
+2

#a = [[1,2,3],[4,5,6],[7,8,9]]
[i for i, j in enumerate(a)  if 5 in j][0]
+2

, :

def find(item, array):
    counter = 0
    for each in array:
        if item in each:
            return counter
        counter = counter + 1
    return None

:

: None -

def find(item, array):
    for idx, each in enumerate(array):
        if item in each:
            return idx
+1

index, :

[x.index(5) for x in array if 5 in x]
+1

enumerate(), :

for elem in array:
     for i in elem:
             if 5 in elem: print array.index(elem)
             break
+1

counter. :

for inner_array in array:
  if inner_array.index(5) > -1:
    return array.index(inner_array);
return None;
0
array = [[1,2,3],[4,5,6],[7,8,9]]
counter = 0

for item in array:
    for n in item:
        if n == 5:
            counter += 1
    print counter

Probably more efficient ways to do this, but it works for me

0
source

I see functional examples, so I'm a bit late:

[(id,inner.index(5)) for id,inner 
 in enumerate(arr) 
 if 5 in inner]
0
source

Source: https://habr.com/ru/post/1675239/


All Articles