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


当前回答

python中的某些结构包含一个索引方法,可以很好地解决这个问题。

'oi tchau'.index('oi')     # 0
['oi','tchau'].index('oi') # 0
('oi','tchau').index('oi') # 0

参考文献:

在列表中

在元组中

字符串中

其他回答

正如@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 index()方法将抛出错误。因此,您可以将其设置为类似于JavaScript的indexOf()函数,如果未找到项,则返回-1:

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

另一种选择

>>> a = ['red', 'blue', 'green', 'red']
>>> b = 'red'
>>> offset = 0;
>>> indices = list()
>>> for i in range(a.count(b)):
...     indices.append(a.index(b,offset))
...     offset = indices[-1]+1
... 
>>> indices
[0, 3]
>>> 
text = ["foo", "bar", "baz"]
target = "bar"

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

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

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

[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

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