2011-01-28 14 views
5

私はPythonが初めてです。私は質問があります。誰かが私を助けることができた。私は、コマンドプロンプトで次の操作を行いセットの結果がPythonで出力される順序

:私はそのの中で結果をプリントアウトすることを理解

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

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

私はそれを印刷するとき私が得る答えは、このようなものですその方法で保存されます。しかし、それを注文する方法はありますか?たとえば、次のように言ってください:

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

ありがとう!

答えて

9

あなたは、セットがその要素をソートされた順序で格納しないことは間違いありません。あなたがセットを必要としない場合は、代わりにセットのリストを使用することができます

>>> 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)] 
2

:あなたはソート順にセット内の要素のリストを取得したい場合は、組み込み関数sortedを使用することができます特徴。

実際に注文セットが必要な場合は、collections.OrderedDictを使用できます。.viewkeys()メソッドを使用すると、セットのようなプロキシを取得できます。辞書をループすると、順番にキーが取得されます。

collections.OrderedDict(またはPython 2.6を使用している場合はOrderedDictの別の実装)を使用して独自のOrderedSetを実装できます。

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) 
関連する問題