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


当前回答

请尝试以下代码:

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

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

其他回答

现在,对于完全不同的事情。。。

……比如在获取索引之前确认项目的存在。这种方法的好处是,函数总是返回一个索引列表——即使它是一个空列表。它也适用于字符串。

def indices(l, val):
    """Always returns a list containing the indices of val in the_list"""
    retval = []
    last = 0
    while val in l[last:]:
            i = l[last:].index(val)
            retval.append(last + i)
            last += i + 1   
    return retval

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

粘贴到交互式python窗口时:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(the_list, val):
...     """Always returns a list containing the indices of val in the_list"""
...     retval = []
...     last = 0
...     while val in the_list[last:]:
...             i = the_list[last:].index(val)
...             retval.append(last + i)
...             last += i + 1   
...     return retval
... 
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>> 

使现代化

经过又一年的python开发,我对自己的原始答案感到有点尴尬,所以为了澄清事实,我当然可以使用上面的代码;然而,获得相同行为的更惯用方法是使用列表理解以及enumerate()函数。

类似于:

def indices(l, val):
    """Always returns a list containing the indices of val in the_list"""
    return [index for index, value in enumerate(l) if value == val]

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

当粘贴到交互式python窗口中时,会产生:

Python 2.7.14 |Anaconda, Inc.| (default, Dec  7 2017, 11:07:58) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(l, val):
...     """Always returns a list containing the indices of val in the_list"""
...     return [index for index, value in enumerate(l) if value == val]
... 
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>> 

现在,在回顾了这个问题和所有答案之后,我意识到这正是FMc在其先前的回答中所建议的。在我最初回答这个问题的时候,我甚至没有看到这个答案,因为我不理解它。

如果上面的一行代码对您仍然没有意义,我强烈建议您使用谷歌“python列表理解”,并花几分钟时间熟悉一下。它只是众多强大功能中的一个,让使用Python开发代码成为一件乐事。

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

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

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

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

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

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

text = ["foo", "bar", "baz"]
target = "bar"

[index for index, value in enumerate(text) if value == target]

对于一个小的元素列表,这会很好。但是,如果列表包含大量元素,最好应用二进制运行时复杂度为O(logn)的搜索.

index()返回值的第一个索引!

|索引(…)|L.index(value,[start,[stop]])->integer--返回值的第一个索引

def all_indices(value, qlist):
    indices = []
    idx = -1
    while True:
        try:
            idx = qlist.index(value, idx+1)
            indices.append(idx)
        except ValueError:
            break
    return indices

all_indices("foo", ["foo","bar","baz","foo"])

如果找不到项,Python index()方法将抛出错误。因此,您可以将其设置为类似于JavaScript的indexOf()函数,如果未找到项,则返回-1:

try:
    index = array.index('search_keyword')
except ValueError:
    index = -1