[Python-Dev] non-integer slice indices?
Skip Montanaro
skip@mojam.com (Skip Montanaro)
Sat, 12 Feb 2000 05:49:33 -0600 (CST)
Greg> Currently, a person can do the following:
Greg> foo[slice('a','abc')] = some_sequence
Well, I'll be damned! To wit:
import types, string, UserDict
class SliceableDict(UserDict.UserDict):
def __setitem__(self, index, val):
if type(index) == types.SliceType:
# val must be a sequence. if it's too short, the last
# value is replicated. if it's too long, the extra values
# are ignored.
# keys between index.start and index.stop are assigned elements
# of val - index.step is ignored
start = index.start
stop = index.stop
keys = self.data.keys()
keys.sort()
j = 0
vl = len(val)
for k in keys:
if index.start <= k < index.stop:
self.data[k] = val[j]
j = min(j+1, vl-1)
else:
self.data[index] = val
def init_range(self, keys, val=None):
for k in keys:
self.data[k] = val
d = SliceableDict()
d.init_range(string.lowercase[0:13], 7)
d[slice('a', 'g')] = [12]
print d.data
Now, about that motivation...
Skip Montanaro | http://www.mojam.com/
skip@mojam.com | http://www.musi-cal.com/
"Languages that change by catering to the tastes of non-users tend not to do
so well." - Doug Landauer