首页 > 解决方案 > 在 python 3 中打印 set continer 时,它无序打印

问题描述

我只是想在 python 中学习集合容器。因此,我使用以下方法创建了一个普通集:

dset = set(['a','c','z','d'])

但是当我打印它时,结果是:

{'c', 'a', 'z', 'd'}

不应该是:

{'a', 'c', 'z', 'd'}

谁能解释为什么输出是这样的?设置数据类型是否有任何默认排序机制?还是我的数学很弱?

标签: pythonpython-3.xset

解决方案


套装不是有序的,它们不是有序的容器,所以你无能为力,

如果你有一个列表并且你想使用 set 然后以有序的方式转换回列表:

print(sorted(set(l),key=l.index)) 

所以没有机会制作有序集

顺便说一句,有一个有序的集合......

下载文件的链接,或者只是复制模块中的代码并导入它,记得删除if __name__ == '__main__'底部的部分

或者pip install boltons,那么:

from boltons.setutils import IndexedSet

然后示例:

>>> from boltons.setutils import IndexedSet
>>> x = IndexedSet(list(range(4)) + list(range(8)))
>>> x
IndexedSet([0, 1, 2, 3, 4, 5, 6, 7])
>>> x - set(range(2))
IndexedSet([2, 3, 4, 5, 6, 7])
>>> x[-1]
7
>>> fcr = IndexedSet('freecreditreport.com')
>>> ''.join(fcr[:fcr.index('.')])
'frecditpo'

链接

或者pip install sortedcontainers

安装后,您可以简单地:

from sortedcontainers import SortedSet
help(SortedSet)

或安装collections_extended

然后示例:

>>> from collections_extended import setlist
>>> sl = setlist('abracadabra')
>>> sl
setlist(('a', 'b', 'r', 'c', 'd'))
>>> sl[3]
'c'
>>> sl[-1]
'd'
>>> 'r' in sl  # testing for inclusion is fast
True
>>> sl.index('d')  # so is finding the index of an element
4
>>> sl.insert(1, 'd')  # inserting an element already in raises a ValueError
ValueError
>>> sl.index('d')
4

链接


推荐阅读