python-3.x - 堆参数必须是 python 3 中的列表
问题描述
我试图实现一个数据结构来返回一个值,使得之前调用了 set (key, value, timestamp_prev),timestamp_prev <= timestamp。我试图在 python 中使用最小堆。有一个错误标记,我不太明白。
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.mapping = collections.defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.mapping[key].append([-timestamp, value])
def get(self, key: str, timestamp: int) -> str :
if not self.mapping[key]:
return ''
heap = heapq.heapify(self.mapping[key])
for pre_stamp, val in heapq.heappop(heap):
if -pre_stamp <= timestamp:
return val
return ''
出现错误:堆参数必须是列表。
但它看起来mapping[key] 返回的值是一个列表。
请指教。谢谢!
解决方案
self.mapping
定义为的事实collections.defaultdict(list)
并不意味着self.mapping[key]
将为每个任意返回一个列表key
。这只是意味着self.mapping[key]
将为每个key
不存在的列表返回一个空列表。
import collections
d = collections.defaultdict(list)
d['a'] = 'not a list'
print(type(d['a']), d['a'])
输出
<class 'str'> not a list
推荐阅读
- powershell - 为什么我运行 ps1 脚本的计划任务不会终止?
- linux - Jenkins 插件的问题
- python - 在 PythonAnywhere 中安装 Firebase SDK
- python - numpy.multiply() 的后端源代码是否设置为多处理/多线程?
- java - 如何在 spel 中为弹簧型材编写 AND 运算符
- parsing - 在 Haskell 中编写深度映射的更好方法?
- excel - 如何编写此评估公式以使变体不返回错误?
- azure-application-insights - 在异常表中的 application Insights Stack Traces 中,正在记录没有行号
- bluetooth-lowenergy - Garmin BLE 心率监测器 - 无法通过蓝牙获取 HRM 数据,我错过了什么?
- python - 如何从配置中为每列设置不同的样式