【发布时间】:2021-02-02 15:49:21
【问题描述】:
我用这段代码来判断对象在python中是否可以散列:
#hashable
number1 = 1.2 #float
number2 = 5 #int
str1 = '123' #str
tuple1 = (1,2,3) #tuple
# unhashable
list1 = [1,2,3] #list
print(hash(list1)) #TypeError: unhashable type: 'list'
set1 = {1,2,3} #set
print(hash(set1)) #TypeError: unhashable type: 'set'
dict1 = {'a':1,'b':2,'c':3} #dict
print(hash(dict1)) #TypeError: unhashable type: 'dict'
def HashableOrUnhashable(obj):
'''
This function will return True or False, the object can be hashed or not be hashed.
'''
try:
hash(obj)
return True
except Exception as ex:
return False
result = HashableOrUnhashable(someObj) #Can be str,int,float,list,tuple,set,dict or others.
if result:
print('This object can be hashed.')
else:
print('This object can not be hashed.')
我觉得我在函数HashableOrUnhashable写的不好。
那么应该如何判断一个对象是否可以hash呢?
【问题讨论】:
-
致电
hash正是您应该检查的方式。 (不要相信那些告诉你使用collections.abc.Hashable或typing.Hashable的人 - 在(1, [2])这样的输入上失败。) -
嗨,这很有帮助。
-
我认为你需要给你的函数一个输入参数...
-
可以,但是输入对象可以是任何东西。
-
@August。这就是为什么它需要一个输入参数。
标签: python