How does Python sort a list of sets?

后端 未结 3 821
忘掉有多难
忘掉有多难 2020-12-06 21:59

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?

Edit: The question an

3条回答
  •  死守一世寂寞
    2020-12-06 22:29

    The __le__ operator on sets define the partial ordering "subset". Therefore the sorted order is undefined.

    {3} < {5} is false, but so is {5} < {3} so the sort algorithm will usually not rearrange them.

    Citation from Python3 documentaton about sets:

    The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: ab.

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

提交回复
热议问题