在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
要扩展我的评论,您可以递归地创建我所称的“类型映射”:
然后使用它来获取结构中的类型:
输出:
那么你的功能就是:
如果您需要处理列表以外的事情,您可以简单地将
isinstance
检查扩展到(list, tuple)
,但是您很快就会遇到问题,比如str
(递归迭代字符串是一个问题,因为单个字符或空字符串本身就是一个iterable,所以您的程序会爆炸)和dict
(排序问题,比较键和/或值…)。你知道吗我这样做的方法是使用以下函数:
它使用各种列表理解来获得列表的深层类型。如果它们不完全相同,则返回
None
。你知道吗所以你可以:
相关问题 更多 >
编程相关推荐