[Python-il] elegant non contiguous slice

Alon Levy alonlevy1 at gmail.com
Thu Dec 30 16:32:26 IST 2010


Why not do exactly what you propose, but without using operator
overloading? that way it isn't
magic anymore, doesn't override expected behavior of the getitem
protocol, and still provides
what's wanted with almost the same amount of chars (call it slice,
myarr=L([0,1.2.3]); myarr.slice([1,2])==myarr([1,2]))

On Thu, Dec 30, 2010 at 7:42 AM, Shai Berger <shai at platonix.com> wrote:
> On Thursday 30 December 2010, Avishalom Shalit wrote:
>> Is there a way to elegantly take the (e.g. ) 2nd 7th and 10th element in a
>> list
>>
>> i.e.
>> more elegant than
>> [arr[x] for x in [1,6,9] ]
>>
>> along the lines of
>> arr[1,6,9]
>>
>
> Not by default, but if it's important to you, you can make it. One way to do
> so: define a class L as a subclass of list, overriding its [] implementation:
>
> class L(list):
>  def __getitem__(self, idx):
>    try:
>      i = iter(idx)
>    except TypeError:
>      return super(L, self).__getitem__(idx)
>    else:
>      return [self[ii] for ii in i]
>
> With this definition in scope,
>
>>>> arr = range(10)
>>>> arr
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> L(arr)[1,6,9]
> [1, 6, 9]
>
> and even
>>>> L(arr)[1,6,9,[2,3]]
> [1, 6, 9, [2, 3]]
>
> Most experienced Python users will frown upon this, though.
> _______________________________________________
> Python-il mailing list
> Python-il at hamakor.org.il
> http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
>



-- 
Alon Levy


More information about the Python-il mailing list