Perl's @foo[3,7,1,-1] ?
Nick Craig-Wood
nick at craig-wood.com
Sat Jun 13 15:29:34 EDT 2009
kj <no.email at please.post> wrote:
>
>
> Switching from Perl here, and having a hard time letting go...
>
> Suppose I have an "array" foo, and that I'm interested in the 4th, 8th,
> second, and last element in that array. In Perl I could write:
>
> my @wanted = @foo[3, 7, 1, -1];
>
> I was a bit surprised when I got this in Python:
>
> >>> wanted = foo[3, 7, 1, -1]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: list indices must be integers
You've just tried to index a list with a tuple...
If foo was a dictionary then this might make sense.
> Granted, Perl's syntax is often obscure and hard-to-read, but in
> this particular case I find it quite transparent and unproblematic,
> and the fictional "pythonized" form above even more so.
>
> The best I've been able to come up with in Python are the somewhat
> Perl-like-in-its-obscurity:
>
> >>> wanted = map(foo.__getitem__, (3, 7, 1, -1))
>
> 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]]
>
> Are these the most idiomatically pythonic forms? Or am I missing
> something better?
Firstly run "import this" at the python interactive interpreter to
remind youself of the philosophical differences between perl and
python. I think the philosophy of python is the major reason why it
is such a good language.
As I transitioned from perl to python it took me a while to let go of
perlisms, and get used to writing a little bit more code (usually of
the order of a few characters only) but which was much much clearer.
Perl is full of cleverness which give you great pleasure to write as a
programmer. However when you or someone else looks at that code later
they don't get that same pleasure - horror is more likely the
reaction! Python just isn't like that.
I'd probably write
wanted = foo[3], foo[7], foo[1], foo[-1]
(assuming you didn't mind having a tuple rather than a list)
or maybe this
wanted = [ foo[i] for i in 3, 7, 1, -1 ]
However I can't think of the last time I wanted to do this - array
elements having individual purposes are usually a sign that you should
be using a different data structure.
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list