Perl's @foo[3,7,1,-1] ?

Piet van Oostrum piet at cs.uu.nl
Sat Jun 13 19:02:16 EDT 2009


>>>>> kj <no.email at please.post> (k) wrote:

>k> Switching from Perl here, and having a hard time letting go...

>k> Suppose I have an "array" foo, and that I'm interested in the 4th, 8th,
>k> second, and last element in that array.  In Perl I could write:

>k>   my @wanted = @foo[3, 7, 1, -1];

>k> I was a bit surprised when I got this in Python:

>>>>> wanted = foo[3, 7, 1, -1]
>k> Traceback (most recent call last):
>k>   File "<stdin>", line 1, in <module>
>k> TypeError: list indices must be integers

>k> Granted, Perl's syntax is often obscure and hard-to-read, but in
>k> this particular case I find it quite transparent and unproblematic,
>k> and the fictional "pythonized" form above even more so.

>k> The best I've been able to come up with in Python are the somewhat
>k> Perl-like-in-its-obscurity:

>>>>> wanted = map(foo.__getitem__, (3, 7, 1, -1))

>k> or the clearer but unaccountably sesquipedalian

>>>>> wanted = [foo[i] for i in 3, 7, 1, -1]
>>>>> wanted = [foo[3], foo[7], foo[7], foo[-1]]

>k> Are these the most idiomatically pythonic forms?  Or am I missing
>k> something better?

Do it yourself:

class MyList(list):
    def __getitem__(self, indx):
        if isinstance (indx, tuple):
            return [self[i] for i in indx]
        else:
            return list.__getitem__(self, indx)

l = MyList((range(10)))

print l[3, 7, 1, -1]
print l[3]
print l[3:7]

# and now for something completely different

print l[3, (7, 1), -1]

duck :=)
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list