Can a List Comprehension do ____ ?

Marc Boeren m.boeren at guidance.nl
Wed Jul 14 10:42:17 CEST 2004


> >>> breaks = [(133, 137), (181, 185), (227, 231), (232, 236), 
> (278, 282),
> (283, 287), (352, 356), (412, 416), (485, 489), (490, 494)]
> >>> it = iter(breaks)
> >>> [(start, end) for ((_, start), (end, _)) in zip(it, it)]
> [(137, 181), (231, 232), (282, 283), (356, 412), (489, 490)]
> >>>

That's not quite the result the OP wanted (it misses e.g. (185, 227)),
but this solution combined with an earlier one (which used a copy of the
list starting at position one) yields the desired result (with the
efficiency of the iterator):

>>> breaks = [(133, 137), (181, 185), (227, 231), (232, 236), (278,
282), (283, 287), (352, 356), (412, 416), (485, 489), (490, 494)]
>>> it = iter(breaks)
>>> it2 = iter(breaks)
>>> it2.next() # from the other solution, which used breaks[1:]
(133, 137)
>>> [(start, end) for ((_, start), (end, _)) in zip(it, it2)]
[(137, 181), (185, 227), (231, 232), (236, 278), (282, 283), (287, 352),
(356, 412), (416, 485), (489, 490)]
>>>

Cheerio, Marc.



More information about the Python-list mailing list