给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?


当前回答

Python方式将使用enumerate,但您也可以使用来自运算符模块的indexOf。请注意,如果b不在a中,这将引发ValueError。

>>> from operator import indexOf
>>>
>>>
>>> help(indexOf)
Help on built-in function indexOf in module _operator:

indexOf(a, b, /)
    Return the first index of b in a.

>>>
>>>
>>> indexOf(("foo", "bar", "baz"), "bar") # with tuple
1
>>> indexOf(["foo", "bar", "baz"], "bar") # with list
1

其他回答

在查找列表中项目的索引时,列表理解将是获得紧凑实现的最佳选择。

a_list = ["a", "b", "a"]
print([index for (index , item) in enumerate(a_list) if item == "a"])

简单地说,你可以

a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']

res = [[x[0] for x in a].index(y) for y in b]

如果元素不在列表中,则会出现问题。此函数处理以下问题:

# if element is found it returns index of element else returns None

def find_element_in_list(element, list_element):
    try:
        index_element = list_element.index(element)
        return index_element
    except ValueError:
        return None

下面是使用Python的index()函数的两行代码:

LIST = ['foo' ,'boo', 'shoo']
print(LIST.index('boo'))

输出:1

me = ["foo", "bar", "baz"]
me.index("bar") 

您可以将此应用于列表中的任何成员以获取其索引