[Python-il] elegant non contiguous slice

Sagiv Malihi sagivmalihi at gmail.com
Thu Dec 30 11:45:05 IST 2010


In case you're actually using an array of numbers, and not a general list,
you can use numpy to do it 'the matlab way':

>>> import numpy
>>> arr = numpy.array([1,2,3,4,5,6])
>>> arr
array([1, 2, 3, 4, 5, 6])
>>> arr[[0,5,-1]]
array([1, 6, 6])

- Sagiv

On Thu, Dec 30, 2010 at 12:55 AM, Rani Hod <rani.hod at gmail.com> wrote:

> Unlike Perl, Python is based upon the principle of having exactly one
>> way to do each thing.
>> List comprehension (the [arr[x] for x in [1,6,9] ] method) is one way to
>> accomplish the goal, and it is reasonably parsimonious.  Therefore, it
>> is very unlikely to have another method of accomplishing the same.
>>
>
> There is another method, but I wouldn't call it elegant.
> It ought to be more efficient, though.
>
> map(arr.__getitem__, (1,6,9))
>
> _______________________________________________
> Python-il mailing list
> Python-il at hamakor.org.il
> http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://hamakor.org.il/pipermail/python-il/attachments/20101230/798b2bec/attachment.htm>


More information about the Python-il mailing list