首页 > 解决方案 > 堆参数必须是 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] 返回的值是一个列表。

请指教。谢谢!

标签: python-3.xheap

解决方案


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

推荐阅读