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


当前回答

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

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

其他回答

这里提出的所有函数都再现了固有的语言行为,但掩盖了正在发生的事情。

[i for i in range(len(mylist)) if mylist[i]==myterm]  # get the indices

[each for each in mylist if each==myterm]             # get the items

mylist.index(myterm) if myterm in mylist else None    # get the first index and fail quietly

如果语言提供了自己想要的方法,为什么要编写带有异常处理的函数?

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

# 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

下面是使用Python的index()函数的两行代码:

LIST = ['foo' ,'boo', 'shoo']
print(LIST.index('boo'))

输出:1

请尝试以下代码:

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

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

FMc和user7177的答案的变体将给出一个可以返回任何条目的所有索引的dict:

>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>> 

您还可以将其用作一行程序来获取单个条目的所有索引。虽然我确实使用了set(a)来减少lambda的调用次数,但并不能保证效率。