slicing return iter?
weasley_wx at sina.com
Sat Oct 17 19:05:52 CEST 2009
On 10月17日, 下午11时56分, Arnaud Delobelle <arno... at googlemail.com> wrote:
> 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.
I had checked it for serval times. maybe it's my inattention :-(. but
what i could find the nearest thing is itertools.islice. but it can't
process negative index -- that's supported by slice. so I need
something, bind object with slice, and return a iter. I can find
anything like it...:-(
More information about the Python-list