Skip to main content
 首页 » 编程设计

python之按值对 python 集列表进行排序

2025年05月04日16Renyi-Fan

frozenset 文档说:

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 sets 的文档说:

Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.

这让我不禁要问:为什么会这样?而且,如果我想按集合内容对集合列表进行排序,我该怎么做?我知道扩展名 intbitset:https://pypi.python.org/pypi/intbitset/2.3.0 , 具有返回表示设置内容的位序列的功能。有没有可以与 python 集相媲美的东西?

请您参考如下方法:

元组、列表、字符串等具有自然的字典顺序并且可以排序,因为您始终可以比较给定集合的两个元素。也就是说,a < b , b < a , 或 a == b .

两组之间的自然比较是 a <= b均值 a是 b 的子集, 这就是表达式 a <= b实际上是用 Python 做的。文档中“部分排序”的意思是并非所有集合都具有可比性。以以下集合为例:

a = {1, 2, 3} 
b = {4, 5, 6} 

是a b 的一个子集?编号是b a 的一个子集?不,它们相等吗?不。如果您根本无法比较它们,您显然无法对它们进行排序。

对一组集合进行排序的唯一方法是,如果您的比较函数实际上可以比较任意两个元素(total order)。这意味着您仍然可以使用上述子集关系对一组集合进行排序,但您必须确保所有集合都具有可比性(例如 [{1}, {1, 2, 4}, {1, 2}])。

做你想做的事情的最简单方法是将每个单独的集合转换成你实际上可以比较的东西。基本上,你做 f(a) <= f(b) (其中 <= 很明显)对于一些简单的函数 f .这是通过 key 完成的关键字参数:

In [10]: def f(some_set): 
   ...       return max(some_set) 
   ... 
 
In [11]: sorted([{1, 2, 3, 999}, {4, 5, 6}, {7, 8, 9}], key=f) 
Out[11]: [{4, 5, 6}, {7, 8, 9}, {1, 2, 3, 999}] 

您正在排序 [f(set1), f(set2), f(set3)]并将结果排序应用于 [set1, set2, set3] .