slicing return iter?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sun Oct 18 22:54:32 EDT 2009
En Sun, 18 Oct 2009 23:07:40 -0200, Raymond Hettinger <python at rcn.com>
escribió:
> [Raymond]
>> > 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]
>
> [StarWing]
>> Thank you. but it can't support negative index :-(
>
> The negative index is handled by the line, "yield seq[i]".
>
>>>> s[-2:-5:-1] == ''.join(myslice(s, -2, -5, -1))
> True
>>>> s[-5:-2:1] == ''.join(myslice(s, -5, -2, 1))
> True
But not always:
py> s[10:-1:1]==''.join(myslice(s, 10, -1, 1))
False
py> s[-10:25:1]==''.join(myslice(s, -10, 25, 1))
False
You have to take the sequence length into account before computing the
range, not after.
--
Gabriel Genellina
More information about the Python-list
mailing list