为什么';Python中的集合是否有sort()方法?

为什么';Python中的集合是否有sort()方法?,python,set,Python,Set,为什么Python的set对象没有sort()方法 >>> dir(set) ['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '

为什么Python的set对象没有
sort()
方法

>>> dir(set)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

因为根据定义,集合不是有序的


但是您可以使用python文档中的。

简短回答从集合
s
中获得排序列表

集合是没有重复元素的无序集合

由于集合只定义偏序(子集关系),因此对于集合列表,list.sort()方法的输出是未定义的


来自流利Python第3章词典和集合的详细答案

了解Python字典和集合是如何使用哈希表实现的有助于理解它们的优点和局限性

List.sort()建立了这样一种约定,即sort()对对象进行就地排序,但集合无法就地排序,因为集合是无序的

可以想象,一个集合可以有一个具有另一个名称的方法,该方法返回其元素的排序列表。但是不需要这样的方法,因为函数sorted()已经完成了这项工作。

您可以调用集合上的
sorted()
,集合根据定义是无序的。如果您想要一个有序的集合,请使用列表。有什么问题吗?可能是重复的
#4: Key ordering depends on insertion order
#5: Adding items to a dict may change the order of existing keys