Separating elements from a list according to preceding element

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Mar 6 02:11:01 CET 2006


Gerard Flanagan a écrit :
> Alex Martelli wrote:
> 
>>Gerard Flanagan <grflanagan at yahoo.co.uk> wrote:
>>    ...
>>
>>>a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]
>>>
>>>import itertools
>>>
>>>b = list(itertools.islice(a,0,8,2))
>>>c = list(itertools.islice(a,1,8,2))
>>
>>Much as I love itertools, this specific task would be best expressed ad
>>
>>b = a[::2]
>>c = a[1::2]
>>
> 
> 
> Yes, I thought that when I saw bruno's solution - I can't say that I've
> never seen that syntax before, but I never really understood that this
> is what it did.

It's in fact pretty simple. The full slice syntax is [start:end:step], 
with default values of start=0, end=len(seq), step=1. So a[::2] will 
retrieve a[0], a[2], a[4] etc, and a[1::2] -> a[1], a[3], a[5] etc.

(snip)



More information about the Python-list mailing list