在子子列表中查找元素的索引 [英] Find index of element in sub-sub-list

查看:73
本文介绍了在子子列表中查找元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list that looks like this:

a = [[[0.0125, 6.6], [0.0125, 6.65], [0.0125, 6.7], [0.0125, 6.75], [0.0125, 6.8]], [[0.0185, 6.6], [0.0185, 6.65], [0.0185, 6.7], [0.0185, 6.75], [0.0185, 6.8]]]

ie:每个子列表中的 N 个子列表(此处仅两个)和 M 个子列表(在此示例中为五个).每个元素/子列表由两个浮点数组成.

ie: N sub-lists (only two here) and M sub-sub-lists in each sub-list (five in this example). Each element/sub-sub-list is made of two floats.

我需要找到给定元素的索引,例如 [0.0185,6.75] .在这种情况下,结果应为: [1,3] .

I need to find the index of a given element, say [0.0185, 6.75]. In this case the result should be: [1, 3].

我不能仅在 a 上应用 .index()运算符,因为该元素位于子列表之一内,并且由于我不知道先验是哪一个,我无法遍历应用该运算符的子列表,因为如果找不到该元素,则会导致错误.

I can't just apply the .index() operator on a since the element is inside one of the sub-lists and since I don't know a priori which one it is I can't loop through the sub-lists applying that operator because it will result in an error if the element is not found.

添加

我在更大的数组(16个子列表和70个子子列表)中尝试了zhangxaochen ans DSM的答案,看看哪个更快,这就是我得到的:

I tried the answers by zhangxaochen ans DSM in a much larger array (16 sub-lists and 70 sub-sub-lists) to see which one was faster and this is what I got:

DSM: 4.31537628174e-05
zhangxaochen: 0.00113296508789

由于DSM的响应速度提高了约26倍,因此我选择了它.谢谢大家!

Since DSM's answer its ~26x faster, I'm selecting that one. Thanks guys!

推荐答案

一种方法是使用 next enumerate :

>>> a = [[[0.0125, 6.6], [0.0125, 6.65], [0.0125, 6.7], [0.0125, 6.75], [0.0125, 6.8]], [[0.0185, 6.6], [0.0185, 6.65], [0.0185, 6.7], [0.0185, 6.75], [0.0185, 6.8]]]
>>> search_for = [0.0185, 6.75]
>>> print next(((i,j) for i,x in enumerate(a) for j,y in enumerate(x) 
...             if y == search_for), None)
(1, 3)
>>> search_for = [0.0185, 99]
>>> print next(((i,j) for i,x in enumerate(a) for j,y in enumerate(x) 
...             if y == search_for), None)
None

但是由于测试浮点数的相等性可能过于敏感,因此您可能希望将 y == search_for 替换为允许某些容忍度的 is_close(y,search_for)函数错误.使用的方法位于 .index 中.

But since testing equality of floats can be too sensitive, you might want to replace y == search_for with an is_close(y, search_for) function which allows some tolerance for error. Methods using is in or .index can't really handle that.

这篇关于在子子列表中查找元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆