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

如何用哈希表直接查找Python类实例,避免遍历所有实例?

用哈希表优化TransType实例的查找效率

核心思路是利用Python字典(哈希表实现),以(交易类型, 交易子类型)元组作为键,直接映射到对应的TransType实例,把原来的O(n)遍历查找改成O(1)的直接查找。

修改后的完整代码

# Financial transactions
###########################################################################################
class IterTransType(type):
    def __iter__(cls):
        return iter(cls._allTransTypes)

class TransType(metaclass=IterTransType):
    _allTransTypes = []
    # 添加类级别的字典,用(类型,子类型)元组作为键存储实例
    _trans_map = {}

    def __init__(self, TransType, TransSubType):
        self._allTransTypes.append(self)
        # 将当前实例存入字典,键是(类型,子类型)元组
        self.__class__._trans_map[(TransType, TransSubType)] = self

        self.TransType = TransType
        self.TransSubType = TransSubType
        self.TotalAmt = 0 
        self.NumTrans = 0 
        self.Lowest = 0
        self.Highest = 0


def RecordTransaction(inTransType,inTransSubType,Amount):
    # 直接通过元组键查找字典,无需遍历
    key = (inTransType, inTransSubType)
    transtype = TransType._trans_map.get(key)
    
    if transtype:
        transtype.TotalAmt += Amount
    else:
        new_trans_type = TransType(inTransType,inTransSubType)
        new_trans_type.TotalAmt = Amount
     
    # end of RecordTransaction


def PlayWithTransactions(csv_file):
    print ('PlayWithTransactions')

    RecordTransaction('Expense_regular','Mortgage',1200)
    RecordTransaction('Expense_regular','Groceries',100)
    RecordTransaction('Expense_one_time','NewSuit',1000)
    RecordTransaction('Income_regular','Paycheck',800)
    RecordTransaction('Expense_regular','Groceries',50)

    print ('Stats:')
    for transtype in TransType:
        print ('Trans type: ' + transtype.TransType + ', subtype: ' + transtype.TransSubType + ", Total Amount: " + str(transtype.TotalAmt))

    # end of PlayWithTransactions

关键改动说明

  • 添加类字典_trans_map:作为类级别的存储容器,所有TransType实例创建时都会以(类型,子类型)元组为键存入该字典,确保每个类型组合唯一对应一个实例。
  • 修改__init__方法:在将实例加入_allTransTypes列表的同时,同步更新_trans_map字典,保证两种存储结构的数据一致性。
  • 重构RecordTransaction函数:使用字典的get方法直接查找目标实例,找不到则创建新实例,彻底消除遍历操作,大幅提升查找效率(尤其当实例数量较多时)。

运行输出

修改后的代码运行输出与原代码完全一致:

PlayWithTransactions
Stats:
Trans type: Expense_regular, subtype: Mortgage, Total Amount: 1200
Trans type: Expense_regular, subtype: Groceries, Total Amount: 150
Trans type: Expense_one_time, subtype: NewSuit, Total Amount: 1000
Trans type: Income_regular, subtype: Paycheck, Total Amount: 800

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:45:38