给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
如果性能令人担忧:
在许多答案中都提到,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]
其他回答
对于一个可比的
# Throws ValueError if nothing is found
some_list = ['foo', 'bar', 'baz'].index('baz')
# some_list == 2
自定义谓词
some_list = [item1, item2, item3]
# Throws StopIteration if nothing is found
# *unless* you provide a second parameter to `next`
index_of_value_you_like = next(
i for i, item in enumerate(some_list)
if item.matches_your_criteria())
按谓词查找所有项的索引
index_of_staff_members = [
i for i, user in enumerate(users)
if user.is_staff()]
如果你想找到一个索引,那么使用“index”方法就可以了。然而,如果您要多次搜索数据,那么我建议使用平分模块。请记住,使用平分模块数据必须进行排序。因此,您对数据进行一次排序,然后可以使用二等分。在我的机器上使用平分模块比使用索引方法快20倍。
以下是使用Python 3.8及以上语法的代码示例:
import bisect
from timeit import timeit
def bisect_search(container, value):
return (
index
if (index := bisect.bisect_left(container, value)) < len(container)
and container[index] == value else -1
)
data = list(range(1000))
# value to search
value = 666
# times to test
ttt = 1000
t1 = timeit(lambda: data.index(value), number=ttt)
t2 = timeit(lambda: bisect_search(data, value), number=ttt)
print(f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")
输出:
t1=0.0400, t2=0.0020, diffs t1/t2=19.60
所有具有zip函数的索引:
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print get_indexes(2, [1, 2, 3, 4, 5, 6, 3, 2, 3, 2])
print get_indexes('f', 'xsfhhttytffsafweef')
简单地说,你可以
a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']
res = [[x[0] for x in a].index(y) for y in b]
在查找列表中项目的索引时,列表理解将是获得紧凑实现的最佳选择。
a_list = ["a", "b", "a"]
print([index for (index , item) in enumerate(a_list) if item == "a"])