Separating elements from a list according to preceding element

Alex Martelli aleaxit at yahoo.com
Sun Mar 5 21:54:33 CET 2006


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]

Do note that you really don't need the 'list(...)' here, for the
following use:

> result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
> result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']

...would be just as good if b and c were islice objects rather than
lists, except for the issue of _repeating_ (izipping twice).  I'd rather
do some variant of a single-loop such as:

results = {'+':[], '-':[]}
for operator, tag in itertools.izip(a[::2], a[1::2]):
    results[operator].append(tag)

and use results['+'] and results['-'] thereafter.

These approaches do not consider the inconvenient fact that the leading
'+' does in fact not appear in list a -- it needs to be assumed, the OP
stated; only a '-' would instead appear explicitly. Little for it but
specialcasing depending on whether a[0]=='-', I think -- e.g. in the
above 3-line snippet of mine, insert right after the first line:

if a[0]!='-': results['+'].append(a.pop(0))


Alex



More information about the Python-list mailing list