如何对包含冻结集的列表进行排序 (python)

How to sort a list containing frozensets (python)

我有一个要排序的 frozensets 列表,每个 frozensets 都包含一个整数值,该值来自两个集之间的交集运算:

k = frozenset(w) & frozenset(string.digits)
d[k] = w # w is the value
list(d) # sorted(d) doesn't work since the keys are sets and sets are unordered.

这是打印的列表:

[frozenset({'2'}), frozenset({'1'}), frozenset({'4'}), frozenset({'3'})]

如何使用集合中包含的值对列表进行排序?

您需要向 sorted 提供 key 函数,它接受 frozenset 作为参数和 return 可以比较的东西。如果每个 frozenset 恰好有 1 个元素并且所述元素始终是个位数,那么您可以使用 max 函数(它将提取该单个元素,因为唯一元素始终是 frozenset 的最大元素)即

d1 = [frozenset({'2'}), frozenset({'1'}), frozenset({'4'}), frozenset({'3'})]
d2 = sorted(d1,key=max)
print(d2)

输出

[frozenset({'1'}), frozenset({'2'}), frozenset({'3'}), frozenset({'4'})]

如果您想了解更多信息,请阅读 Sorting HOW TO

老实说,除非您真的需要将元素保持为 frozenset,否则最好的办法是在上游生成一个值列表 ([2, 1, 4, 3])。

无论如何,为了能够对 frozensets 进行排序,您需要使它们成为有序元素,例如通过转换为 tuple。您可以使用 sorted

key 参数透明地执行此操作
l = [frozenset({'2'}), frozenset({'1'}), frozenset({'4'}), frozenset({'3'})]

sorted(l, key=tuple)

natsorted 用于多位数字的字符串:

from natsort import natsorted
l = [frozenset({'2'}), frozenset({'1'}), frozenset({'14'}), frozenset({'3'})]

natsorted(l, key=tuple)

输出:

[frozenset({'1'}), frozenset({'2'}), frozenset({'3'}), frozenset({'14'})]

之前的答案无法正确排序,因为字符串

d = [frozenset({'224'}), frozenset({'346'}), frozenset({'2'}), frozenset({'22345'})]
sorted(d, key=lambda x: int(list(x)[0]))

输出:

[frozenset({'2'}),
 frozenset({'224'}),
 frozenset({'346'}),
 frozenset({'22345'})]