作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用结构模式匹配,如何编写匹配可散列类型实例的案例?
我试过:
for obj in [], (), set(), frozenset(), 10, None, dict():
match obj:
case object(__hash__=_):
print('Hashable type: ', type(obj))
case _:
print('Unhashable type: ', type(obj))
但是,这得到了错误的答案,因为每种类型都定义了 __hash__
是否可散列:
Hashable type: <class 'list'>
Hashable type: <class 'tuple'>
Hashable type: <class 'set'>
Hashable type: <class 'frozenset'>
Hashable type: <class 'int'>
Hashable type: <class 'NoneType'>
Hashable type: <class 'dict'>
最佳答案
Raymond Hettinger 的答案在有限的情况下有效,但它在像 list
(类型对象本身)这样的输入上失败,即使 list.__hash__ 是 None
,它也是可哈希的,和像 ([1, 2], [3, 4])
这样的输入,即使 tuple.__hash__ 不是 None
也是不可散列的。
检测对象是否可哈希的最可靠方法始终是尝试对其进行哈希处理。如果您想在 match
语句中执行此操作,最简单的方法是编写一个守卫:
def hashable(x):
try:
hash(x)
except TypeError:
return False
else:
return True
match x:
case _ if hashable(x):
...
...
这只是直接调用 hash(x)
并查看它是否有效,而不是尝试执行结构检查。
如果需要散列又想避免重复计算,可以保存hash(x)
结果:
def try_hash(x):
try:
return hash(x)
except TypeError:
return None
match x:
case _ if (x_hash := try_hash(x)) is not None:
...
...
关于python - 如何使用结构模式匹配检测可散列类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69848884/
我是一名优秀的程序员,十分优秀!