簡體   English   中英

如何檢查在給定的對象列表中,每種不同類型的對象是否具有可比性?

[英]How to check if, in a given list of objects, each different type of object is comparable?

作為防御性編程的一種手段,我實現了一段相當簡單的代碼來檢查傳遞給我的函數的給定列表的所有元素(不同類型)是否通過比較運算符相互比較(有一個或所有的豐富比較方法)。

我對此的看法是迭代列表並將可用類型與字典中每個對象的單個實例一起編目,然后遍歷字典的鍵,將每個選定的對象相互比較以查看它們是否返回布爾值或引發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.')

出於好奇,是否有更簡潔的方法通過內置的python 或庫來做到這一點?

您所要做的就是嘗試對列表進行排序。

try:
    sorted(list_of_elements)
    print('Objects in list are comparable.')
except TypeError:
    print('Objects in list are not comparable.')

我不確定我是否正確理解了你的問題,但我認為你可以做一些相當簡單的事情,比如:

def check_type(test) :
  for i in test :
    if type(test[i])!=type(test[0]) :
      return False
  return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM