在python中,很容易测试两个变量是否具有相同的顶级类型:

In [1]: s1 = 'bob'
In [2]: s2 = 'tom'
In [3]: type(s1) == type(s2)
Out[3]: True

但在嵌套类型的情况下,就不那么容易了:
In [4]: strlist = ['bob', 'tom']
In [5]: intlist = [5, 6, 7]
In [6]: type(strlist) == type(intlist)
Out[6]: True

有没有一种“深入”比较两个变量的通用方法,以便:
deepcompare(['a', 'b'], [1, 2]) == False
deepcompare([42, 43], [1, 2]) == True

?
编辑:
要进一步定义问题,假设这包括列表长度和异构列表类型:
deepcompare([1, 2, 3], [1, 2]) == False
deepcompare([1, 3], [2, 'b']) == False
deepcompare([1, 'a'], [2, 'b']) == True

最佳答案

要扩展我的评论,您可以递归地创建我所称的“类型映射”:

def typemap(lst_or_obj):
    if not isinstance(lst_or_obj, list):
        return type(lst_or_obj)
    return [typemap(obj) for obj in lst_or_obj]

然后使用此项获取结构中的类型:
a = [1, 2, ['three', 4]]
b = [5, 6, ['seven', 8]]
c = [9, 10, [11, 'twelve']]

ta = typemap(a)
tb = typemap(b)
tc = typemap(c)

print(ta)
print(tb)
print(tc)

print(ta == tb)
print(ta == tc)

输出:
[<class 'int'>, <class 'int'>, [<class 'str'>, <class 'int'>]]
[<class 'int'>, <class 'int'>, [<class 'str'>, <class 'int'>]]
[<class 'int'>, <class 'int'>, [<class 'int'>, <class 'str'>]]
True
False

那么你的功能就是:
def deepcompare(a, b):
    return typemap(a) == typemap(b)

如果您需要处理列表以外的事情,可以简单地将isinstance检查扩展到(list, tuple),但是您很快就会遇到诸如str(递归迭代字符串是一个问题,因为单个字符或空字符串本身是一个iterable,所以您的程序会爆炸)和dict(排序问题、比较键和/或值,…)。

10-04 23:05
查看更多