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


当前回答

正如@TerryA所指出的,许多答案讨论了如何找到一个索引。

moreintertools是一个第三方库,它提供了在可迭代文件中查找多个索引的工具。

鉴于

import more_itertools as mit


iterable = ["foo", "bar", "baz", "ham", "foo", "bar", "baz"]

Code

查找多个观测值的索引:

list(mit.locate(iterable, lambda x: x == "bar"))
# [1, 5]

测试多个项目:

list(mit.locate(iterable, lambda x: x in {"bar", "ham"}))
# [1, 3, 5]

另请参阅more_itertools.locate的更多选项。通过>pip Install more_itertools安装。

其他回答

该值可能不存在,因此为了避免此ValueError,我们可以检查列表中是否确实存在该值。

list =  ["foo", "bar", "baz"]

item_to_find = "foo"

if item_to_find in list:
      index = list.index(item_to_find)
      print("Index of the item is " + str(index))
else:
    print("That word does not exist") 

要获取所有索引,请执行以下操作:

indexes = [i for i, x in enumerate(xs) if x == 'foo']

如果性能令人担忧:

在许多答案中都提到,list.index(item)方法的内置方法是一个O(n)算法。如果您需要执行一次,这是很好的。但是,如果您需要多次访问元素的索引,那么首先创建一个项目索引对的字典(O(n)),然后在每次需要时访问O(1)处的索引更有意义。

如果您确定列表中的项目从未重复,您可以轻松地:

myList = ["foo", "bar", "baz"]

# Create the dictionary
myDict = dict((e,i) for i,e in enumerate(myList))

# Lookup
myDict["bar"] # Returns 1
# myDict.get("blah") if you don't want an error to be raised if element not found.

如果您可能有重复的元素,并且需要返回它们的所有索引:

from collections import defaultdict as dd
myList = ["foo", "bar", "bar", "baz", "foo"]

# Create the dictionary
myDict = dd(list)
for i,e in enumerate(myList):
    myDict[e].append(i)

# Lookup
myDict["foo"] # Returns [0, 4]

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 = ['red', 'blue', 'green', 'red']
>>> b = 'red'
>>> offset = 0;
>>> indices = list()
>>> for i in range(a.count(b)):
...     indices.append(a.index(b,offset))
...     offset = indices[-1]+1
... 
>>> indices
[0, 3]
>>>