给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
现在,对于完全不同的事情。。。
……比如在获取索引之前确认项目的存在。这种方法的好处是,函数总是返回一个索引列表——即使它是一个空列表。它也适用于字符串。
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开发代码成为一件乐事。
其他回答
a = ["foo","bar","baz",'bar','any','much']
indexes = [index for index in range(len(a)) if a[index] == 'bar']
简单选项:
a = ["foo", "bar", "baz"]
[i for i in range(len(a)) if a[i].find("bar") != -1]
text = ["foo", "bar", "baz"]
target = "bar"
[index for index, value in enumerate(text) if value == target]
对于一个小的元素列表,这会很好。但是,如果列表包含大量元素,最好应用二进制运行时复杂度为O(logn)的搜索.
python中的某些结构包含一个索引方法,可以很好地解决这个问题。
'oi tchau'.index('oi') # 0
['oi','tchau'].index('oi') # 0
('oi','tchau').index('oi') # 0
参考文献:
在列表中
在元组中
字符串中
me = ["foo", "bar", "baz"]
me.index("bar")
您可以将此应用于列表中的任何成员以获取其索引