patternpythonCritical
Does Python have an ordered set?
Viewed 0 times
havepythonsetdoesordered
Problem
Python has an ordered dictionary. What about an ordered set?
Solution
There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.
This is a MutableSet, so the signature for
OrderedSet([1, 2, 3])This is a MutableSet, so the signature for
.union doesn't match that of set, but since it includes __or__ something similar can easily be added:@staticmethod
def union(*sets):
union = OrderedSet()
union.union(*sets)
return union
def union(self, *sets):
for set in sets:
self |= setCode Snippets
OrderedSet([1, 2, 3])@staticmethod
def union(*sets):
union = OrderedSet()
union.union(*sets)
return union
def union(self, *sets):
for set in sets:
self |= setContext
Stack Overflow Q#1653970, score: 258
Revisions (0)
No revisions yet.