python - 在 python 3 中打印 set continer 时,它无序打印
问题描述
我只是想在 python 中学习集合容器。因此,我使用以下方法创建了一个普通集:
dset = set(['a','c','z','d'])
但是当我打印它时,结果是:
{'c', 'a', 'z', 'd'}
不应该是:
{'a', 'c', 'z', 'd'}
谁能解释为什么输出是这样的?设置数据类型是否有任何默认排序机制?还是我的数学很弱?
解决方案
套装不是有序的,它们不是有序的容器,所以你无能为力,
如果你有一个列表并且你想使用 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
见链接
推荐阅读
- html - 我试过寻找答案,但没有一个答案有帮助。如何将选项与中心对齐?
- excel - 对于 excel,对于 SUMIF 中的多个参数,如何根据单元格地址添加条件条件?
- django - 如何在 Django 1.9 中覆盖 Spyne 的 call_wrapper 方法?
- python - 返回 3D scipy.spatial.Delaunay 的 z 值
- reactjs - 虚拟化选择:如何在特定标签上进行搜索
- android - Android Studio:多活动问题,活动不移动到下一个活动
- php - 为什么Yii 2什么都没有加载
- azure - 使用 Azure 文件共享中的配置在 Azure 中运行 docker 容器(蚊子代理)
- c# - 如何使用 nodatime 获取所有美国时区 ID
- mysql - 通过检查用户和团队的两个映射表来获取项目