Home > front end >  Get index from 2d array where first element is the index
Get index from 2d array where first element is the index

Time:10-19

I have a 2D array that prints out the following:

[[0, {'dt_name': 'Go'}], [1, {'dt_name': 'Stop'}]]

I want to iterate through this list, so that I can retrieve the index value (first element) if dt_name is Go for example. I.e. return should be 0. If dt_name is Stop, then return is 1.

How can I do this?

CodePudding user response:

You can try this:

>>> a = [[0, {'dt_name': 'Go'}], [1, {'dt_name': 'Stop'}]]
>>> [index] = [x for [x, t] in a if t['dt_name'] == 'Go']
>>> index
0

CodePudding user response:

You have to iterate though the list and check for your condition and in case you got it, you can break out of it and get your index.

As an example:

a = [[0, {'dt_name': 'Go'}], [1, {'dt_name': 'Stop'}]]
ans_idx = -1
for item in a:
  if item[1]['dt_name']=='go':
    ans_idx = item[0]
    break

if ans_idx=-1, that means you don't have an index for the same.

CodePudding user response:

You can do this with function like below:

def fnd_idx(lst, wrd):
    for l in lst:
        if l[1]['dt_name'] == wrd:
            return l[0]
    return -1

Output:

>>> lst = [[0, {'dt_name': 'Go'}], [1, {'dt_name': 'Stop'}]]

>>> fnd_idx(lst, 'Go')
0

>>> fnd_idx(lst, 'Stop')
1

>>> fnd_idx(lst, 'Start')
-1

CodePudding user response:

One approach is to use next on a generator expression

lst = [[0, {'dt_name': 'Go'}], [1, {'dt_name': 'Stop'}]]
res = next(i for (i, t) in lst if t['dt_name'] == 'Go')
print(res)

Output

0

This approach avoids building any additional list.

Some timings on list vs generator:

lst = [[0, {'dt_name': 'Go'}], [1, {'dt_name': 'Stop'}]] * 100
%timeit next(i for (i, t) in lst if t['dt_name'] == 'Go')
452 ns ± 2.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit [i for (i, t) in lst if t['dt_name'] == 'Go'][0]
12.1 µs ± 36.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In the above example using next on the generator is about 24 times faster.

  • Related