slicing return iter?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Oct 18 23:30:16 CEST 2009


En Sun, 18 Oct 2009 03:02:27 -0200, StarWing <weasley_wx at sina.com>  
escribió:

> On 10月18日, 上午9时09分, Raymond Hettinger <pyt... at rcn.com> wrote:
>> [StarWing]
>>
>> > > > sometimes I want to iterate a part of a sequence. but don't want  
>> to
>> > > > copy it. i.e.
>>  . . .
>> > 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...:-(
>>
>> If it really is a sequence (with len and getitem), you can write your
>> own indexing iterator:
>>
>>   def myslice(seq, start, stop, step):
>>        'Allow forward or backwards iteration over a subslice'
>>        for i in range(start, stop, step):
>>            yield seq[i]
>>
>> Raymond
>
> Thank you. but it can't support negative index :-(
> Terry Reedy is right. since a range (or xrange or slice etc.) don't
> have a length, so it can't support a negative index. so the best way
> to do it is that binding a range with a object. and return a iter.
>
> I think, why standard library didn't have anything like that, that
> will be very useful. maybe we should have a builtin functoin
> itertools.bslice (stands for bind slice)...

A variation of the code above would do, using a slice() object:

py> def myslice(seq, start, stop, step):
...   'Allow forward or backwards iteration over a subslice'
...   for i in xrange(*slice(start, stop, step).indices(len(seq))):
...     yield seq[i]
...
py> import string
py> lst = list(string.lowercase)
py> list(myslice(lst, 5, 18, 2)) # as in lst[5:18:2]
['f', 'h', 'j', 'l', 'n', 'p', 'r']
py> list(myslice(lst, -5, None, None))  # as in lst[-5:]
['v', 'w', 'x', 'y', 'z']
py>py> list(myslice(lst, None, None, -1))  # as in lst[::-1]
['z', 'y', 'x', 'w', 'v', 'u', 't', 's', ..., 'a']

Slice objects are not-so-well known, and are documented here:
http://docs.python.org/reference/datamodel.html#types

-- 
Gabriel Genellina




More information about the Python-list mailing list