繁体   English   中英

在给定子列表的元素(Python)的情况下,查找列表中元素索引的最有效方法是什么

[英]What is the most efficient way to find the index of an element in a list, given only an element of a sublist (Python)

即存在以下类似的东西?

lst = [["a", "b", "c"], [4,5,6],"test"]
print getIndex(lst, "a")
>>> 0
print getIndex(lst, 5)
>>> 1
print getIndex(lst, "test")
>>> 2

我知道常规的index()方法,但只查找直接元素。 我有一个粗略的解决方案,即创建一个新列表,解析超级列表并添加“y”或“n”然后在那个中查找“y”的索引,但我觉得有更好的方法。 谢谢

hellpanderrr的解决方案存在问题。 它假定主列表元素只是列表或字符串。 如果名单上搜索其中一种类型是,在主列表(它失败in操作提出了一个TypeError )。 例如:

lst2 = [["a", "b", "c"], [4, 5, 6], "test", 19]


>>> getIndex(lst2, 19)
# Ugly TypeError stack trace ensues

解决这个问题:

def getIndex2(lst, item):
    for n, i in enumerate(lst):
        try:
            if item == i or item in i:
                return n
        except TypeError:
            pass
    return None

现在:

>>> getIndex2(lst2, "test")
2
>>> getIndex2(lst2, 19)
3

有几种方法可以完成“等于或在”测试。 该解决方案碗的权利,通过使用一个“得到宽恕不许可”成语赶在时代ini不是类型合适。 也可以in操作之前测试i的类型,或者直接询问i支持操作。 但直接类型检查通常不受欢迎,Python中的字符串和容器具有一些复杂的重叠功能。 “得到宽恕”的方法更优雅地处理这些问题。

请注意,这也明确处理没有找到值的情况。

>>> print getIndex2(lst2, 333)
None

虽然未返回值的函数隐式返回None ,但最好明确说明此类默认情况。

通过这种方法,这种方法处理两个级别。 如果列表可以任意嵌套,则需要一种可能涉及递归的不同方法。

使用发电机

例如,在> = Python 2.6中,如果您知道该项目存在于子列表中:

idx = next(i for i,v in enumerate(lst) if item in v)
def getIndex(lst,item):
    for n,i in enumerate(lst):
        if (type(i) == list and item in i) or i == item
            return n
getIndex(lst,'test')
>>> 2

尝试使用列表中的默认函数: list.index

l = [[1,2,3], ['a', 'b', 'c']]

l[0].index(2)  # index 1
l[1].index('b') # index 1

This generates a "ValueError" if the item does not exist.

暂无
暂无

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

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