[Tutor] slice lists and slicing syntax questions
Dave Kuhlman
dkuhlman at rexx.com
Sat Oct 13 22:55:59 CEST 2007
On Sat, Oct 13, 2007 at 10:32:39AM -0400, Michael Langford wrote:
> On 10/12/07, gregg at lind-beil.net < gregg at lind-beil.net> wrote:
> >
> > I have been using Python for years now, in all kinds of environments, but
> > example: x is vector of length 5, with value "a","b","c","d","e" , then:
> >
> > x[3,1,1,1,3,2] # gives [d, b, b, b, d, c]
> >
> > What is the python equivalent?
>
> a. Am I understanding the situation correctly?
>
> When you call [] on an object, it calls __getitem__The definition for
> getitem is __getitem__(self,key), where key can be an integer or a slice
> object. Slice objects are either a range or a range+step. You've got the
> right picture
__getitem__() suggests a Pythonic solution: subclass list and override
__getitem__():
class subscriptlist(list):
def __getitem__(self, subscripts):
#print 'type(subscripts):', type(subscripts)
if (isinstance(subscripts, tuple) or
isinstance(subscripts, list)):
vals = []
for subscript in subscripts:
vals.append(list.__getitem__(self, subscript))
return vals
else:
val = list.__getitem__(self, subscripts)
return val
def test():
a = range(10)
b = [x * 5 for x in a]
c = subscriptlist(b)
d = c[2,5,6,8]
print 'd:', d
e = c[2]
print 'e:', e
test()
Which prints out:
d: [10, 25, 30, 40]
e: 10
Was that what you wanted?
Notice that "c[2,5,6,8]" results in passing a tuple to __getitem__,
because it is the comma that marks a literal representation of a
tuple.
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
More information about the Tutor
mailing list