作為防御性編程的一種手段,我實(shí)現(xiàn)了一段相當(dāng)簡(jiǎn)單的代碼來檢查傳遞給我的函數(shù)的給定列表的所有元素(不同類型)是否可以通過比較運(yùn)算符(有一個(gè)或所有實(shí)施的豐富比較方法)。我對(duì)此的看法是迭代列表并編目可用類型以及字典中每個(gè)對(duì)象的單個(gè)實(shí)例,然后運(yùn)行字典的鍵,將每個(gè)選定的對(duì)象相互比較以查看它們是否返回布爾值或引發(fā)TypeError.下面是我的想法的實(shí)現(xiàn):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)] = elemcmp = Truefor 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: breakif cmp: print('Objects in list are comparable.')else: print('Objects in list are not comparable.')只是出于好奇,是否有一種更簡(jiǎn)潔的方法可以通過 python 內(nèi)置或庫(kù)來執(zhí)行此操作?
2 回答

白板的微信
TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
您所要做的就是嘗試對(duì)列表進(jìn)行排序。
try:
sorted(list_of_elements)
print('Objects in list are comparable.')
except TypeError:
print('Objects in list are not comparable.')

千萬(wàn)里不及你
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
我不確定我是否正確理解你的問題,但我認(rèn)為你可以做一些相當(dāng)簡(jiǎn)單的事情,例如:
def check_type(test) :
for i in test :
if type(test[i])!=type(test[0]) :
return False
return True
添加回答
舉報(bào)
0/150
提交
取消