如何在python中对集合进行排序? [英] How to sort a set in python?

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

问题描述

我正在尝试通过向其中添加元素来对 Python 中的集合进行排序.我尝试使用 sorted() 方法,但它正在将我的集合转换为列表.我需要对我的元素进行排序并将其打印为一个集合.我该怎么做?

我尝试使用 sorted() 方法并获得了一个列表.试图将列表放入一个集合中.但是,没有收到要求的结果

a={}a=set()a.添加(1)a.添加(-1)a.添加(0)a.添加(4)a.添加(-3)打印(一)

预期结果:{-3, -1, 0, 1, 4}实际结果:{0, 1, 4, -3, -1}

解决方案

你不能

只需阅读 python 文档:

<块引用>

Python 还包括集合的数据类型.集合是没有重复元素的无序集合.基本用途包括成员资格测试和消除重复条目.集合对象还支持并、交、差、对称差等数学运算.

强调我的.

这意味着您将永远无法对集合中的项目进行排序*.

至少,对于普通"集合,你不能.您应该更好地寻找第三方库(默认字典和 collections.OrderedDict),因为我认为 python 没有内置有序集,至少在 collections.

*嗯,不是从不,我知道早期版本的 python 没有订购字典,现在他们有.但至少在当前版本(python 3.7)中,没有有序集.

无论如何,字典的工作方式与集合类似.在字典中,你不能有两次相同的键,就像在一个集合中你不能有两次相同的项目.因此,如果您使用字典的键并忽略这些键的值,collections.OrderedDict 可能适合您.从 Python 3.7 开始,即使是基本词典(使用 dict() 制作的词典)也可以使用.

<预><代码>>>>a = dict()>>>a[1] = 无>>>a[-1] = 无>>>a[0] = 无>>>a[4] = 无>>>a[-3] = 无>>>打印(a.keys())dict_keys([1, -1, 0, 4, -3])

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}

解决方案

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])

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

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