How to sort a set in python? [duplicate]

风格不统一 提交于 2020-07-18 22:31:23

问题


I am trying to sort a set in python, by adding elements to it. I tried using the sorted() method, but it is converting my set into a list. I need to sort my elements and print it as a set itself. How can I do that?

I tried using the sorted() method and obtained a list. Tried to put the list into a set. But, didn't receive the required result

a={}
a=set()
a.add(1)
a.add(-1)
a.add(0)
a.add(4)
a.add(-3)
print(a)

Expected result: {-3, -1, 0, 1, 4} Actual result: {0, 1, 4, -3, -1}


回答1:


You can't

Just read python documentation:

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Emphasis mine.

That means you will never be able to sort items inside a set*.

At least, with "normal" sets, you can't. You should better look for third-party libraries (both, default dictionaries and collections.OrderedDict), because I don't think that python has inbuilt ordered sets, at least no in collections.

*Well, not never, I have understood that early versions of python hadn't ordered dictionaries, and now they have. But at least in the current version (python 3.7), there aren't ordered sets.

Anyway, dictionaries work in a similar manner to sets. In a dictionary, you can't have two times the same key, like in a set you can't have two times the same item. So if you work with the keys of a dictionary and just ignore the values of those keys, a collections.OrderedDict may work for you. Even base dictionaries (those you make with dict()) will work since Python 3.7.

>>> a = dict()
>>> a[1] = None
>>> a[-1] = None
>>> a[0] = None
>>> a[4] = None
>>> a[-3] = None
>>> print(a.keys())
dict_keys([1, -1, 0, 4, -3])


来源:https://stackoverflow.com/questions/55389165/how-to-sort-a-set-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!