Python如何对集合列表进行排序? [英] How does Python sort a list of sets?

查看:1880
本文介绍了Python如何对集合列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python通过按顺序查看元组的元素来对元组列表进行排序.由于集合是无序的,Python如何对集合列表进行排序?

Python sorts lists of tuples by looking at the elements of the tuples, in order. Since sets are unordered, how does Python sort a list of sets?

这篇文章中的问题和已接受的答案较为笼统给出的文件非常深入.我的问题不是重复.

The question and accepted answer in this post are more general and the document given is very in-depth. My question is not a duplicate.

推荐答案

无论列表中有什么内容,元素的__lt__方法都是参考的唯一比较方法.对于集合,a < b表示"ab的适当子集",这不足以定义总顺序.这就是为什么结果通常是不确定的.可能是原始列表的任何排列,与实现恰巧将__lt__应用于哪些列表元素对一致.

Regardless of what's in a list, the elements' __lt__ methods are the only comparison methods consulted. For sets, a < b means "a is a proper subset of b", which isn't enough to define a total order. That's why the result is, in general, undefined. It may be any permutation of the original list consistent with which pairs of list elements the implementation happens to apply __lt__ to.

如果对于列表中的每对集合,一个实际上是另一个的适当子集,则列表将从最小(基数)设置为最大.否则,无话可说.例如:

If, for every pair of sets in the list, one is in fact a proper subset of the other, then the list will be sorted from smallest (cardinality) set to largest. Otherwise little can be said. For example:

>>> sorted([{5, 6}, {3, 4}, {5}, {3}])  # nothing changes
[{5, 6}, {3, 4}, {5}, {3}]

发生的事情是未定义实现细节的结果.自从我写了list.sort()以来,我知道在这种情况下会发生什么,但是不能保证总是这样工作:

What happens is a consequence of undefined implementation details. Since I wrote list.sort(), I know what happens in this case, but it's not guaranteed to always work this way:

首先,实现询问是{3, 4} < {5, 6}?".不可以,因此前两个元素的顺序与已经排序的顺序是一致的.接下来询问"{5} < {3, 4}?".否,因此前三个元素似乎已经被排序.最后,它询问"{3} < {5}?".不会再出现了,因此原始列表的整个顺序与已经排序的顺序是一致的,并且没有任何变化.

First the implementation asks "is {3, 4} < {5, 6}?". No, so the order of the first two elements is consistent with being sorted already. It next asks "is {5} < {3, 4}?". No, so the first three elements appear to be already sorted. Finally it asks "is {3} < {5}?". No again, so the original list's entire order is consistent with being already sorted, and nothing changes.

例如,将来的实现可能会问是{5} < {5, 6}吗?".在某些时候,由于是",因此决定{5}需要出现在{5, 6}之前.因此,结果根本没有定义.

A future implementation may, e.g., ask "is {5} < {5, 6}?" at some point, and since "yes" decide {5} needs to appear before {5, 6}. So the result is simply not defined.

这篇关于Python如何对集合列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆