I\'m new to Python. I\'ve a question. Some one could help me.
I do the following in the command prompt:
>>> a=set()
>>> for i in ra
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)