【问题标题】:When printing set continer in python 3, it prints it without order [duplicate]在python 3中打印集合容器时,它没有顺序打印它[重复]
【发布时间】:2018-10-16 07:09:48
【问题描述】:

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

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

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

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

不应该吗:

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

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

【问题讨论】:

  • 集合不是有序容器。如果你想订购,你必须使用列表或元组
  • 如果你一遍又一遍地运行它,你可能会得到相同的输出,但这个输出不是你可以指望得到的。
  • 我认为this 是你想要的。 pypi中有一个模块ordered-set
  • @exabytes.js - 由于它们的主要用途,不需要有订单,它有助于性能。见Python Sets vs Lists
  • @Sayse 是的,这有帮助。谢谢!

标签: python python-3.x set


【解决方案1】:

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

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

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

所以没有机会制作有序集

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

link to download file, or just copy the code in a module and import it, remember to remove the if __name__ == '__main__' part in the bottom

或者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'

link

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

link

【讨论】:

    【解决方案2】:

    来自文档 (https://docs.python.org/3.7/library/stdtypes.html#set-types-set-frozenset):

    集合对象是不同的可散列对象的无序集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多