简体   繁体   English

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

[英]How to sort a list containing frozensets (python)

I have a list of frozensets that I'd like to sort, Each of the frozensets contains a single integer value that results from an intersection operation between two sets:我有一个要排序的冻结集列表,每个冻结集都包含一个 integer 值,该值是由两组之间的交集运算产生的:

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.

Here is the printed list:这是打印的列表:

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

How can I sort the list using the values contained in the sets?如何使用集合中包含的值对列表进行排序?

You need to provide function as key to sorted which would accept frozenset as argument and return something which might be compared.您需要提供 function 作为sortedkey ,它将接受frozenset作为参数并返回可能进行比较的内容。 If each frozenset has exactly 1 element and said element is always single digit then you might use max function (it will extract that single element, as sole element is always biggest element of frozenset ) that is如果每个frozenset恰好有 1 个元素并且所述元素始终是单个数字,那么您可以使用max function (它将提取该单个元素,因为唯一元素始终是frozenset的最大元素),即

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

output output

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

If you want to know more read Sorting HOW TO如果您想了解更多信息,请阅读如何排序

Honestly, unless you really need to keep the elements as frozenset , the best might be to generate a list of values upstream ( [2, 1, 4, 3] ).老实说,除非您真的需要将元素保留为frozenset ,否则最好的方法可能是生成上游值列表( [2, 1, 4, 3] )。

Anyway, to be able to sort the frozensets you need to make them ordered elements, for instance by converting to tuple .无论如何,为了能够对冻结集进行排序,您需要使它们成为有序元素,例如通过转换为tuple You can do this transparently using the key parameter of sorted or natsorted for strings :您可以使用字符串的sortednatsortedkey参数透明地执行此操作:

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

natsorted(l, key=tuple)

output: output:

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

Previous answers can not sorted correctly, Because of strings以前的答案无法正确排序,因为字符串

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

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM