Why Python does *SLICING* the way it does??
Mike Meyer
mwm at mired.org
Fri Apr 22 01:43:41 EDT 2005
Roy Smith <roy at panix.com> writes:
> Greg Ewing <greg at cosc.canterbury.ac.nz> wrote:
>> Also, everyone, please keep in mind that you always have
>> the option of using a *dictionary*, in which case your
>> indices can start wherever you want.
>>
>> You can't slice them, true, but you can't have everything. :-)
>
> Of course you can slice them, you just have to subclass dict! The
> following was about 15 minutes work:
>
> ---------------
> import types
>
> class slicableDict (dict):
> def __getitem__ (self, index):
> if type (index) == types.SliceType:
> d2 = slicableDict()
> for key in self.keys():
> if key >= index.start and key < index.stop:
> d2[key] = self[key]
> return d2
> else:
> return dict.__getitem__ (self, index)
>
> d = slicableDict()
> d['hen'] = 1
> d['ducks'] = 2
> d['geese'] = 3
> d['oysters'] = 4
> d['porpoises'] = 5
>
> print d
> print d['a':'m']
> ---------------
I couldn't resist:
py> d = slicableDict()
py> d[3j] = 1
py> d[4j] = 2
py> d[5j] = 3
py> d[6j] = 4
py> d[4j:5j]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in __getitem__
TypeError: cannot compare complex numbers using <, <=, >, >=
Somehow, that seems like a wart.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list