堆参数必须是 python 中的列表 3

Heap argument must be a list in python 3

我正在尝试为 returns 一个值实现一个数据结构,这样之前调用了 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 '' 

出现错误:堆参数必须是列表。

但看起来映射[key]返回的值是一个列表。

请指教。谢谢!

self.mapping 定义为 collections.defaultdict(list) 的事实并不意味着 self.mapping[key] 将 return 为每个任意 key 的列表。这只是意味着 self.mapping[key] 将为 return 每个 存在的 key 列表将 return 一个空列表。

import collections

d = collections.defaultdict(list)
d['a'] = 'not a list'
print(type(d['a']), d['a'])

产出

<class 'str'> not a list