Can a List Comprehension do ____ ?
Andrew Bennetts
andrew-pythonlist at puzzling.org
Wed Jul 14 03:52:21 EDT 2004
On Tue, Jul 13, 2004 at 11:22:08PM -0800, Eric @ Zomething wrote:
> Pythonistas,
>
> I seem at a loss for a List Comprehension syntax that will do what I want.
>
> I have a list of string position spans:
>
> >>> breaks
> [(133, 137), (181, 185), (227, 231), (232, 236), (278, 282), (283, 287), (352, 356), (412, 416), (485, 489), (490, 494)]
>
> the first pair representing: someString[133:137]
>
> What I want is a list of the positions between these spans, which would look like this:
>
> >>> spans
> [[(137, 181)], [(185, 227)], [(231, 232)], [(236, 278)], [(282, 283)], [(287, 352)], [(356, 412)], [(416, 485)], [(489, 490)]]
This can do it:
>>> breaks = [(133, 137), (181, 185), (227, 231), (232, 236), (278, 282),
... (283, 287), (352, 356), (412, 416), (485, 489), (490, 494)]
>>> spans = [(x[1],y[0]) for x,y in zip(breaks, breaks[1:])]
>>> spans
[(137, 181), (185, 227), (231, 232), (236, 278), (282, 283), (287, 352), (356, 412), (416, 485), (489, 490)]
> Of course I can get such a list, but I haven't been able to figure out how
> to do this with a List Comprehension. I am wondering if there is a syntax
> which makes pairs of the maximum of one list element and the minimum of
> the next list element.
>
> Can anyone show me the List Comprehensions light?
Well, as you can see, the trick is that list comprehensions only operate on
one element at a time, and you wanted to deal with two elements. My
solution deals with that by zipping breaks and breaks[1:] together.
-Andrew.
More information about the Python-list
mailing list