【发布时间】:2021-07-17 19:24:32
【问题描述】:
对于我的项目,我需要在列表中反复查找时间戳的索引,以及是否准确的时间戳 不在列表中我需要在我要查找的时间戳之前找到时间戳的索引。 我尝试遍历列表,但这很慢:
def find_item_index(arr, x):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
for index in range(len(arr)):
if arr[index] <= x < arr[index+1]:
return index
raise ValueError(f'{x} not in array.')
我也尝试过递归,但速度更慢:
def find_item_index_recursive(arr, x, index = 0):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
length = len(arr)
if length == 1:
return index
if arr[length // 2] < x:
return find_item_index_recursive(arr[length // 2:], x, index + length // 2)
else:
return find_item_index_recursive(arr[:length // 2], x, index)
raise ValueError(f'{x} not in array.')
有更快的方法吗?
【问题讨论】:
-
递归方法很慢,因为您通过切片制作了大量副本。将开始/结束索引与原始列表一起传递,它应该很快。
-
排序并使用bisect!
-
排序肯定比在列表中循环一个循环要慢@ti7
-
这能回答你的问题吗? Fastest way to find Indexes of item in list?
-
@PranavHosangadi 肯定是,但他们需要重复找到一些东西并暗示列表已排序(否则为什么索引很重要?)
标签: python list performance recursion search