如何检查在给定的对象列表中,每种不同类型的对象是否具有可比性?

0 python types list python-3.x

作为防御性编程的一种手段,我实现了一段相当简单的代码来检查传递给我的函数的给定列表的所有元素(不同类型)是否通过比较运算符相互比较(具有一个或所有的丰富比较方法)。

我对此的看法是迭代列表并将可用类型与字典中每个对象的单个实例一起编目,然后遍历字典的键,将每个选定的对象相互比较以查看它们是否返回布尔值或提高一个TypeError.

下面是我的想法的实现:

test = [1, 2, 'str', 4.5, {'r':'d'}]

type_dict = {}
for elem in test:
    if not isinstance(elem, tuple(type_dict.keys())):
        type_dict[type(elem)] = elem
cmp = True
for obj1 in type_dict.keys():
    for obj2 in type_dict.keys():
        try:
            type_dict.get(obj1) > type_dict.get(obj2)
        except TypeError:
            cmp = False
            break
    if not cmp:
        break
if cmp:
    print('Objects in list are comparable.')
else:
    print('Objects in list are not comparable.')
Run Code Online (Sandbox Code Playgroud)

出于好奇,是否有更简洁的方法通过内置的python 或库来做到这一点?

Dee*_*ace 5

您所要做的就是尝试对列表进行排序。

try:
    sorted(list_of_elements)
    print('Objects in list are comparable.')
except TypeError:
    print('Objects in list are not comparable.')
Run Code Online (Sandbox Code Playgroud)