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


当前回答

简单地说,你可以

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

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

其他回答

name ="bar"
list = [["foo", 1], ["bar", 2], ["baz", 3]]
new_list=[]
for item in list:
    new_list.append(item[0])
print(new_list)
try:
    location= new_list.index(name)
except:
    location=-1
print (location)

这说明了如果字符串不在列表中,如果它不在列表,则位置=-1

对此有一个更实用的答案。

list(filter(lambda x: x[1]=="bar",enumerate(["foo", "bar", "baz", "bar", "baz", "bar", "a", "b", "c"])))

更通用的形式:

def get_index_of(lst, element):
    return list(map(lambda x: x[0],\
       (list(filter(lambda x: x[1]==element, enumerate(lst))))))

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

a_list = ["a", "b", "a"]
print([index for (index , item) in enumerate(a_list) if item == "a"])
a = ["foo","bar","baz",'bar','any','much']

indexes = [index for index in range(len(a)) if a[index] == 'bar']

如果性能令人担忧:

在许多答案中都提到,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]