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

如何实现包含子类型的对象类型深度比较

比较包含子类型的对象类型解决方案

核心需求说明

我们需要对比的是对象的类型结构,而非实际存储的值,约束条件如下:

  • 仅处理JSON兼容类型:字典、列表、整数、字符串、浮点数、布尔值、None
  • 不考虑混合子类型场景:比如同时包含整数和字符串的列表、键/值类型不一致的字典
  • 基础版本仅向下比较两层深度,也提供不限深度的通用实现

两层深度简化实现

def compare_type_two_level(obj1, obj2):
    # 第一层:判断外层类型是否一致
    if type(obj1) != type(obj2):
        return False
    obj_type = type(obj1)
    
    # 基础类型直接返回True
    if obj_type in (int, str, float, bool, type(None)):
        return True
    # 列表类型:判断子元素类型
    elif obj_type == list:
        if len(obj1) == 0 or len(obj2) == 0:
            return len(obj1) == len(obj2)
        return type(obj1[0]) == type(obj2[0])
    # 字典类型:判断键类型、值的类型
    elif obj_type == dict:
        if len(obj1) == 0 or len(obj2) == 0:
            return len(obj1) == len(obj2)
        # 取第一个键值对判断类型
        k1, v1 = next(iter(obj1.items()))
        k2, v2 = next(iter(obj2.items()))
        # 第二层:判断键类型、值的外层类型
        if type(k1) != type(k2):
            return False
        return type(v1) == type(v2)

测试验证

# 示例1:不同子类型的列表
lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
print(compare_type_two_level(lst1, lst2)) # 输出False

# 示例2:键值类型结构一致的字典
dct1 = {'a': [1, 2, 3]}
dct2 = {'b': [4, 5, 6]}
print(compare_type_two_level(dct1, dct2)) # 输出True

不限深度通用实现

如果需要支持更深层级的类型结构对比,可以用递归实现:

def compare_type_recursive(obj1, obj2):
    if type(obj1) != type(obj2):
        return False
    obj_type = type(obj1)
    
    if obj_type in (int, str, float, bool, type(None)):
        return True
    elif obj_type == list:
        if len(obj1) == 0 or len(obj2) == 0:
            return len(obj1) == len(obj2)
        return compare_type_recursive(obj1[0], obj2[0])
    elif obj_type == dict:
        if len(obj1) == 0 or len(obj2) == 0:
            return len(obj1) == len(obj2)
        k1, v1 = next(iter(obj1.items()))
        k2, v2 = next(iter(obj2.items()))
        return compare_type_recursive(k1, k2) and compare_type_recursive(v1, v2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:54:07