slicing return iter?
Arnaud Delobelle
arnodel at googlemail.com
Sat Oct 17 11:56:46 EDT 2009
On Oct 17, 3:40 pm, StarWing <weasley... at sina.com> wrote:
> hello everyone, I'm new here :-)
>
> sometimes I want to iterate a part of a sequence. but don't want to
> copy it. i.e.
>
> a = list(...)
> # now a is a list, and a[:] is another list, and so a[m:n]
> # now we do something with the 0~len(a)-3 elements of a
> for val in a[:-2]:
> #do something....
>
> but, this will cause a copy on a, has some convenience way to get a
> iter to iterate on a part of list?
>
> i made this:
> class iterslice:
> def __init__(self, list):
> self.list = list
>
> def __len__(self):
> return len(self.list)
>
> def __getitem__(self, slice):
> import itertools
> listlen = len(self.list)
> range = (((slice.start + listlen) % listlen) if slice.start
> else 0,
> ((slice.stop + listlen) % listlen) if slice.stop else
> listlen,
> slice.step)
> return itertools.islice(self.list, *range)
>
> a = [1,2,3,4]
> for i in iterslice(a)[:-1:2]:
> print i
>
> my question is:
> - are there any *Standard* way to do this? (a buit-in function? a
> module?)
> - are there any better implements?
>
> thanks for attention :-)
Check the itertools module.
HTH
--
Arnaud
More information about the Python-list
mailing list