套装不是有序的,它们不是有序的容器,所以你无能为力,
如果你有一个列表并且你想使用 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