caasswa
caasswa

Reputation: 521

Get index from 2d array where first element is the index

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?

Upvotes: 2

Views: 696

Answers (4)

Dani Mesejo
Dani Mesejo

Reputation: 61910

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.

Upvotes: 1

I'mahdi
I'mahdi

Reputation: 24049

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

Upvotes: 1

avats
avats

Reputation: 445

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.

Upvotes: 1

sushant
sushant

Reputation: 1111

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

Upvotes: 1

Related Questions