排序的键值数据存储,其中键是浮点数,值是对象

Sorted key-value data store where keys are float and values are objects

我正在尝试制作一个简单的基于时间的脚本,其中用户输入:

  1. 启动脚本调用对象后的时间,称为 dt_call
    • time.perf_counter() 生成(也称为 float
  2. 反对当时打电话

是否有 Python 库具有满足以下条件的键值存储?

  1. 键是float
  2. 值为 object
  3. 键已排序

更多信息

这将是调度程序的一部分,其中每隔一段时间调度程序:

  1. 获取脚本启动后的当前时间(秒),调用 dt
  2. 也许调用该对象,取决于它的调用时间是否已过
    1. 看看if dT >= dt_call
    2. 如果是:检查关联对象是否被调用。如果未调用,则调用该对象。
    3. 如果否:什么都不做

当前最佳创意

目前,我最好的想法是基于此:Sort a list of tuples by 2nd item (integer value)

开始脚本之前:

  1. dt_call + 对象对存储在 tuple
  2. 将所有对存储在列表中
  3. 使用此排序:
# Keys are `dt_call`
list_.sort(key=lambda x:x[0])

list_  # [(5.6, obj0), (5.9, obj1), (8.7, obj2)]

启动脚本后:

  1. 使用bisect.bisect
  2. 获得index
  3. 查看是否调用了 index - 1 处的对象。如果没有,调用它。
# Start
start_time = time.perf_counter()

# Some time has passed
dt = time.perf_counter() - start_time

# Step 1
index = bisect.bisect([x[0] for x in list_], dt)

# Step 2
fetched_obj = list_[index - 1][1]
if fetched_obj.is_not_called():
    fetched_obj()

有没有我可以使用的数据结构以更直接的方式(一体式)完成此任务?

这个想法结合了多种数据结构来完成工作。

你提到需要一个数据结构允许:

Keys as floats
Values are objects
Sorting of Keys

会推荐模块
Heapq

非常适合组织元组列表的项目

  • tuple order controlled by elements in the tuple

  • objects can be values in the tuple

  • heap order is updated as items are added or deleted

  • Takes O(log(n)) in time to add or remove an item

计时器

from time import perf_counter 

使用堆

from heapq import heappush, heappop

heap = []   # any heap

项目是元组

# delay from current time to perform action on object
scheduled_time = perf_counter() + delay
item = (scheduled_time , obji)  # i-th object

将对象添加到堆

heappush(heap, item)

假设堆是一个项目列表,我们有一个计划:

我们使用以下循环处理堆中的对象

While True:

    # heap[0] is almost the smallest for a heap so
    scheduled_time, obj = heap[0]

    if perf_counter() >= schedule_time:
        # pop earliest off heap and do something
        heappop(heap)
        do_something(obj)

堆在heappop(删除和项目)或heappush(添加项目)时自动重新排序时间最早的项目