You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python SortedSet实现按元组时间戳排序、按字符串搜索?

解决方案

核心思路

用SortedSet负责按时间戳排序存储元组,同时搭配一个普通字典建立字符串到元组的映射,既能满足排序需求,又能实现快速按字符串检索。

具体实现代码

from sortedcontainers import SortedSet

# 初始化SortedSet,指定排序键为元组的第二个元素(时间戳)
sorted_set = SortedSet(key=lambda x: x[1])
# 字典用于字符串到元组的快速查找
str_mapping = {}

# 添加元素的方法
def add_string_with_timestamp(s, timestamp):
    item = (s, timestamp)
    # 避免同一字符串重复存储(业务允许重复可去掉此判断)
    if s not in str_mapping:
        sorted_set.add(item)
        str_mapping[s] = item

# 按字符串检索元素的方法
def get_item_by_string(s):
    return str_mapping.get(s, None)

# 示例使用
add_string_with_timestamp("hello", 1620000000)
add_string_with_timestamp("world", 1620000001)

# 按字符串搜索
print(get_item_by_string("hello"))  # 输出: ('hello', 1620000000)

# 遍历SortedSet,会按时间戳升序输出
for item in sorted_set:
    print(item)
# 输出顺序: ('hello', 1620000000), ('world', 1620000001)

关键点说明

  • SortedSet的key参数:通过key=lambda x: x[1]指定排序依据为元组的时间戳字段,集合内元素会自动按时间戳从小到大排序。
  • 字典的作用:SortedSet本身无法直接通过字符串快速定位元素,字典str_mapping以字符串为键、对应元组为值,实现O(1)时间复杂度的字符串检索。
  • 去重逻辑:添加元素时先检查字符串是否已存在,避免同一字符串对应多个时间戳的冲突(若业务场景允许重复字符串,可移除该判断,SortedSet会保留所有不同的元组)。

内容的提问来源于stack exchange,提问作者Abhijit Sarkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:22:11