简体   繁体   English

从二维数组中获取索引,其中第一个元素是索引

[英]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.我想遍历这个列表,以便我可以检索索引值(第一个元素),例如如果dt_nameGo Ie return should be 0 .即回报应该是0 If dt_name is Stop , then return is 1 .如果dt_nameStop ,则 return 是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.如果ans_idx=-1 ,这意味着您没有相同的索引。

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一种方法是在生成器表达式上使用next

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.在上面的例子中,在生成器上使用 next 大约快 24 倍。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM