如何深入比较Python中的嵌套类型

2024-09-30 18:28:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

Tags: infalsetrue类型列表typeout顶级
2条回答

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

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(排序问题,比较键和/或值…)。你知道吗

我这样做的方法是使用以下函数:

def getDeepTypes(items):
    types = [type(x) for x in items]
    return (types[0] if all(x == types[0] for x in types) else None)

它使用各种列表理解来获得列表的深层类型。如果它们不完全相同,则返回None。你知道吗

>>> getDeepTypes([1, 2, 3])
int
>>> getDeepTypes(["foo", "bar"])
str
>>> print(getDeepTypes([1, "foo"]))
None

所以你可以:

getDeepTypes(['a', 'b']) == getDeepTypes([1, 2]) # False
getDeepTypes([42, 43]) == getDeepTypes([1, 2]) # True

相关问题 更多 >