开发者

the order in which result of a set is printed in Python

开发者 https://www.devze.com 2023-02-07 21:29 出处:网络
I do the following in the command prompt: >>> a=set() >>> for i in range(0,8): ...a.add((i,j))

I do the following in the command prompt:

>>> a=set()
>>> for i in range(0,8):
...     a.add((i,j))
... 

the answer that I get when I print it is like this:

>>> a
set([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])

I understand that its printing out the results in the way its stored开发者_如何学Go. But is there a way I can get it ordered? Say for example in this way:

(0,7), (1,7), (2,7), (3,7), ...


You are right that a set doesn't store its elements in sorted order. If you want to get a list of the elements in the set in sorted order you can use the built-in function sorted:

>>> a
set([(2, 7), (4, 7), (6, 7), (5, 7), (7, 7), (0, 7), (1, 7), (3, 7)])
>>> sorted(a)
[(0, 7), (1, 7), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (7, 7)]


You can use a list instead of a set if you don't need the set features.

If you really want an ordered set, on Python 2.7 you can use collections.OrderedDict, the .viewkeys() method can be used to get a set-like proxy, while looping over the dictionary will get you the keys in order.

Or you can implement your own OrderedSet using collections.MutableSet and collections.OrderedDict (or another implementation of OrderedDict if you have Python 2.6).

class OrderedSet(collections.MutableSet):
    def __init__(self, iterable=[]):
        self._data = collections.OrderedDict((x, None) for x in iterable)

    def __contains__(self, x):
        return x in self._data

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

    def __le__(self, other):
        if isinstance(other, OrderedSet) and hasattr(self._data, 'viewkeys'):
            return self._data.viewkeys() <= other._data.viewkeys()
        return super(OrderedSet, self).__le__(other)

    def add(self, value):
        self._data[value] = None

    def discard(self, value):
        self._data.pop(value, None)

    def remove(self, value):
        self._data.pop(value)

    def pop(self):
        return self._data.popitem()[0]

    def clear(self):
        self._data.clear()

    def __ior__(self, other):
        self._data.update((x, None) for x in other)
        return self

    def __iand__(self, other):
        if not isinstance(other, collections.Set):
            other = self._from_iterable(other)
        for value in list(self._data):
            if value not in other:
                self.remove(value)
        return self

    def __and__(self, other):
        if not isinstance(other, collections.Iterable):
            return NotImplemented
        if not isinstance(other, collections.Set):
            other = self._from_iterable(other)
        return self._from_iterable(value for value in self if value in other)
0

精彩评论

暂无评论...
验证码 换一张
取 消