slicing lists

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Wed May 7 21:43:57 EDT 2008


On May 7, 6:13 pm, Miles <semantic... at gmail.com> wrote:

(snipped)

>  I think Yves meant to return [1, 3, 4, 5, 6], as in Perl's list slicing:
>
>  my @x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
>  return @x[0, 2..6]; // returns (1, 3, 4, 5, 6)
>
>  This isn't incredibly efficient, but it does what you want (I think):
>
>  from itertools import chain
>
>  class multisliceable(list):
>   def __getitem__(self, slices):
>     if isinstance(slices, (slice, int, long)):
>       return list.__getitem__(self, slices)
>     else:
>       return list(chain(*[list.__getitem__(self, s) if isinstance(s, slice)
>                           else [list.__getitem__(self, s)] for s in slices]))
>
>  p = open('/etc/passwd')
>  q = [multisliceable(e.strip().split(':'))[0,2:] for e in p]
>
>  -Miles



There's also the operator module:

import itertools
import operator

idx = [one for one in itertools.chain([0], range(2, 6))]

wanted = operator.itemgetter(*idx)

q = [wanted(line.strip().split(':')) for line in file("/etc/passwd")]

--
Hope this helps,
Steven



More information about the Python-list mailing list