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


当前回答

如果需要所有索引,则可以使用NumPy:

import numpy as np

array = [1, 2, 1, 3, 4, 5, 1]
item = 1
np_array = np.array(array)
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)

这是一个清晰易读的解决方案。

其他回答

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

# 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

正如@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安装。

不要。如果您确实需要,请使用列表中的.index(item…)方法。然而,这需要线性的时间,如果你发现自己正在努力,你可能会滥用列表来做一些你不应该做的事情。

最有可能的是,您关心1)整数和项目之间的双向映射,或2)在已排序的项目列表中查找项目。

对于第一个,使用一对字典。如果您需要一个库来实现这一点,请使用双向库。

对于第二个,使用可以正确利用列表排序这一事实的方法。使用python中内置的平分模块。

如果您希望在排序列表中插入项目,也不应使用排序列表。使用内置的heapq模块或使用sortedcontainers库将已排序的需求弱化为堆。

使用一个不是为你想做的事情而设计的数据结构是不好的做法。使用一个与你给它的任务相匹配的数据结构,既会向读者传达你想做特定的事情,也会使你的解决方案在实践中更快/更具可扩展性。

查找列表L中项目x的索引:

idx = L.index(x) if (x in L) else -1

可以使用zip()函数获取列表中值的索引。代码可以是:;

list1 = ["foo","bar","baz"]
for index,value in zip(range(0,len(list1)),list1):
    if value == "bar":
        print(index)