frozensets 之间的平等

Equality between frozensets

示例:

>>> tuple((1, 2)) == tuple((2, 1))
False
>>> frozenset((1, 2)) == frozenset((2, 1))
True

冻结集是不可变的。我希望不可变对象之间的相等性应该由顺序决定,但显然情况并非如此。

如何在不转换为不同类型的情况下丢弃具有相同元素和不同顺序的 frozensets?

简短的回答是你不能,因为正如评论中所指出的,sets 和 frozensets 是无序的数据结构。以下是 docs* 的一些摘录来支持这一说法:

A set object is an unordered collection of distinct hashable objects.

There are currently two built-in set types, set and frozenset. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

* Python 2.7.12


为了更好地理解平等问题,我鼓励您使用 Online Python Tutor 运行 以下代码段:

tup_1 = tuple((1, 2))
tup_2 = tuple((2, 1))
fs_1 = frozenset((1, 2))
fs_2 = frozenset((2, 1))

这是一个非常方便的工具,可以在逐步执行代码的同时呈现内存中对象的图形表示。我附上截图:

Tonechas 的回答是错误的。

frozenset是无序的,但是可以用来做相等比较。引自python官方doc:

Both set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).