gpt4 book ai didi

python - 如何使用结构模式匹配检测可散列类型?

转载 作者:行者123 更新时间:2023-12-02 16:04:20 25 4
gpt4 key购买 nike

使用结构模式匹配,如何编写匹配可散列类型实例的案例?

我试过:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com