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

Python存储带频次条目、支持弹出时计数递减的数据结构推荐

解决方案

首先需要注意:Python 中列表是可变不可哈希类型,无法直接作为字典的 key,你可以把条目标为元组来实现相同的存储效果,比如把["item1","property1"]改为("item1","property1")。

你可以基于 Python 标准库的collections.Counter封装自定义类来满足需求,以下是可直接运行的实现:

from collections import Counter
import random

class FrequencyCounter:
    def __init__(self, items=None):
        # 初始化时自动把输入的列表类条目转成元组当key
        self.counter = Counter()
        if items:
            for item, freq in items.items():
                self.counter[tuple(item)] = freq
    
    def popitem(self, item=None):
        # 传入指定条目则弹出对应条目,不传则随机弹出有效条目
        if item is not None:
            item_tuple = tuple(item)
            if item_tuple not in self.counter or self.counter[item_tuple] <= 0:
                raise KeyError(f"Item {item} not exists or frequency is 0")
            self.counter[item_tuple] -= 1
            return list(item_tuple)
        valid_items = [item for item, cnt in self.counter.items() if cnt > 0]
        if not valid_items:
            raise KeyError("No valid items to pop")
        selected = random.choice(valid_items)
        self.counter[selected] -= 1
        return list(selected)
    
    # 方便打印查看当前结构
    def __repr__(self):
        return str({list(k):v for k,v in self.counter.items()})

使用示例

# 初始化结构
fc = FrequencyCounter({
    ["item1","property1"]:10, 
    ["item2","property2"]:5,
    ["item3","property3"]:5
})
print(fc) 
# 输出:{['item1', 'property1']: 10, ['item2', 'property2']: 5, ['item3', 'property3']: 5}

# 调用popitem弹出指定条目
res = fc.popitem(["item3","property3"])
print(res) 
# 输出:['item3', 'property3']
print(fc) 
# 输出:{['item1', 'property1']: 10, ['item2', 'property2']: 5, ['item3', 'property3']: 4}

# 无参调用popitem随机弹出有效条目
res2 = fc.popitem()
print(res2)
print(fc)

如果需要每次弹出频次最高/最低的条目,只需要修改无参逻辑里的条目选择规则,按频次排序后取对应条目即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:18:04