finding indices in a sequence of parentheses
Steven Bethard
steven.bethard at gmail.com
Sun May 29 21:19:40 EDT 2005
tiissa wrote:
> I'd personnally extract the parenthesis then zip the lists of indices.
> In short:
>
> >>> def indices(mylist):
> ... lopen=reduce(list.__add__, [[i]*s.count('(') for i,s in
> enumerate(mylist)],[])
> ... lclose=reduce(list.__add__, [[i]*s.count(')') for i,s in
> enumerate(mylist)],[])
> ... return zip(lopen,lclose)
> ...
> >>> indices(lst)
> [(2, 2), (4, 7), (6, 7), (8, 9), (8, 10)]
> >>>
Thanks, that's a good idea. In case anyone else is reading this thread,
and had to mentally unwrap the reduce expressions, I believe they could
be written as:
lopen = [x for i, s in enumerate(lst) for x in [i]*s.count('(')]
lclose = [x for i, s in enumerate(lst) for x in [i]*s.count(')')]
or maybe:
lopen = [i for i, s in enumerate(lst) for _ in xrange(s.count('('))]
lclose = [i for i, s in enumerate(lst) for _ in xrange(s.count(')'))]
Sorry, I have an irrational fear of reduce. ;)
STeVe
More information about the Python-list
mailing list