gpt4 book ai didi

python - 为什么我不能让Python设置不同?

转载 作者:行者123 更新时间:2023-11-28 21:10:29 25 4
gpt4 key购买 nike

所以我做了一些经验:

>>>{2,3} - {2}
{3}

这个非常好用。

但是,这个好像不行:

>>> {{2,3},{4,3}} - {{4,3}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

我认为它应该有效,

因为我使用一组包含两个元素 {2,3} 和 {4,3} 来减去一个元素 {4,3}。

尽管如此,它还是行不通。为什么?

最佳答案

set 不可散列;不能是集合的成员。使用 frozenset相反:

>>> {frozenset({2,3}), frozenset({4,3})} - {frozenset({4,3})}
set([frozenset([2, 3])])

根据 set / frozenset documentation :

The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.


hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().

关于python - 为什么我不能让Python设置不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36612881/

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