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. Ie return should be 0
. If dt_name
is Stop
, then return is 1
.
How can I do this?
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.
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
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.