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

时间:2015-09-28 20:32:11

标签: python list python-2.7 indexing nested-lists

即。是否存在以下内容?

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”的索引,但我觉得有更好的方法。感谢

4 个答案:

答案 0 :(得分:2)

There is a problem with hellpanderrr's solution. It assumes that the main list elements will only be lists or strings. It fails if one searches on a list where another type is in the main list (the in operation raises a TypeError). E.g.:

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


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

To fix this:

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

Now:

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

There are several ways to accomplish the "equals or in" test. This solution bowls right through, using a "get forgiveness not permission" idiom to catch the times when the in on i is not type-appropriate. It would also be possible to test the type of i before the in operation, or directly ask if i supports the in operation. But direct type inspection is often frowned upon, and strings and containers in Python have some complex overlapping capabilities. The "get forgiveness" approach gracefully handles those more simply.

Note that this also explicitly handles the case where no value is found.

>>> print getIndex2(lst2, 333)
None

While functions not returning a value implicitly return None, it is better to be explicit about such default cases.

By the by, this approach handles two levels. If the lists can be arbitrarily nested, a different approach, likely involving recursion, would be needed.

答案 1 :(得分:1)

使用发电机

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

idx = next(i for i,v in enumerate(lst) if item in v)

答案 2 :(得分:0)

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

答案 3 :(得分:0)

尝试使用列表中的默认功能: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.