Perl's @foo[3,7,1,-1] ?
Arnaud Delobelle
arnodel at googlemail.com
Sat Jun 13 15:59:49 EDT 2009
kj <no.email at please.post> writes:
> 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
>
> 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?
You're missing operator.itemgetter:
>>> from operator import itemgetter
>>> foo = "spam & eggs"
>>> itemgetter(3, 7, 1, -1)(foo)
('m', 'e', 'p', 's')
>>>
--
Arnaud
More information about the Python-list
mailing list