给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?
当前回答
如果性能令人担忧:
在许多答案中都提到,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]
其他回答
要获取所有索引,请执行以下操作:
indexes = [i for i, x in enumerate(xs) if x == 'foo']
另一种选择
>>> 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]
>>>
正如@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安装。
>>> ["foo", "bar", "baz"].index("bar")
1
有关列表的内置.index()方法,请参阅文档:
list.index(x[,start[,end]])返回值等于x的第一项列表中从零开始的索引。如果没有该项,则引发ValueError。可选参数start和end被解释为切片符号,用于将搜索限制在列表的特定子序列。返回的索引是相对于完整序列的开头而不是start参数计算的。
注意事项
列表长度的线性时间复杂性
索引调用按顺序检查列表中的每个元素,直到找到匹配项。如果列表很长,并且不能保证值会接近开始,这会降低代码的速度。
只有使用不同的数据结构才能完全避免这个问题。但是,如果已知元素在列表的某个部分内,则可以使用start和end参数来缩小搜索范围。
例如:
>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
第二次调用速度快了几个数量级,因为它只需要搜索10个元素,而不是全部100万个元素。
仅返回第一个匹配项的索引
对索引的调用按顺序搜索列表,直到找到匹配项,然后停止。如果该值可能出现多次,并且需要所有索引,则索引无法解决问题:
>>> [1, 1].index(1) # the `1` index is not found.
0
相反,使用列表理解或生成器表达式进行搜索,使用enumerate获取索引:
>>> # A list comprehension gives a list of indices directly:
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> # A generator comprehension gives us an iterable object...
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> # which can be used in a `for` loop, or manually iterated with `next`:
>>> next(g)
0
>>> next(g)
2
如果只有一个匹配项,列表理解和生成器表达式技术仍然有效,并且更具通用性。
如果不匹配,则引发异常
如以上文档中所述,如果搜索的值不在列表中,则使用.index将引发异常:
>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
如果这是一个问题,请首先使用my_list中的项显式检查,或者根据需要使用try/except处理异常。
显式检查简单易读,但它必须再次迭代列表。参见Python中的EAFP原理是什么?以获取有关此选择的更多指导。
获取列表中一个或多个(相同)项的所有出现次数和位置
使用enumerate(list),您可以存储第一个元素(n),当元素x等于您查找的值时,该元素是列表的索引。
>>> alist = ['foo', 'spam', 'egg', 'foo']
>>> foo_indexes = [n for n,x in enumerate(alist) if x=='foo']
>>> foo_indexes
[0, 3]
>>>
让我们让函数findindex
此函数将项和列表作为参数,并返回项在列表中的位置,就像我们之前看到的那样。
def indexlist(item2find, list_or_string):
"Returns all indexes of an item in a list or a string"
return [n for n,item in enumerate(list_or_string) if item==item2find]
print(indexlist("1", "010101010"))
输出
[1, 3, 5, 7]
易于理解的
for n, i in enumerate([1, 2, 3, 4, 1]):
if i == 1:
print(n)
输出:
0
4
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象