给定一个列表[“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安装。

其他回答

它只使用python函数array.index()和简单的Try/Except,如果在列表中找到记录,则返回该记录的位置,如果没有在列表中发现,则返回-1(就像在JavaScript中使用函数indexOf())。

fruits = ['apple', 'banana', 'cherry']

try:
  pos = fruits.index("mango")
except:
  pos = -1

在这种情况下,“mango”不在列表水果中,因此pos变量为-1,如果我搜索了“cherry”,pos变量将为2。

使用字典,首先处理列表,然后将索引添加到其中

from collections import defaultdict

index_dict = defaultdict(list)    
word_list =  ['foo','bar','baz','bar','any', 'foo', 'much']

for word_index in range(len(word_list)) :
    index_dict[word_list[word_index]].append(word_index)

word_index_to_find = 'foo'       
print(index_dict[word_index_to_find])

# output :  [0, 5]

简单地说,你可以

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

请尝试以下代码:

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

参考:https://www.programiz.com/python-programming/methods/list/index