[Tutor] String slicing from tuple list

Kent Johnson kent37 at tds.net
Thu Jul 21 22:05:08 CEST 2005


cgw501 at york.ac.uk wrote:
> Hi,
> 
> I have a list of tuples like this:
> 
> [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)]
> 
> Each tuple references coordinates of a big long string and they are in the 
> 'right' order, i.e. earliest coordinate first within each tuple, and 
> eearliest tuple first in the list. What I want to do is use this list of 
> coordinates to retrieve the parts of the string *between* each tuple. So in 
> my example I would want the slices [2367:6457], [8345:9086] and 
> [10100:12304]. Hope this is clear.

You could write a for loop that keeps some state. Another way is to preprocess the lists into what you want. zip() makes this easy:
 >>> data = [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)]
 >>>
 >>> first, second = zip(*data)
 >>> first
(1423, 6457, 9086, 12304)
 >>> second
(2637, 8345, 10100, 15666)
 >>> starts = second[:-1]
 >>> starts
(2637, 8345, 10100)
 >>> ends = first[1:]
 >>> ends
(6457, 9086, 12304)
 >>> ranges = zip(starts, ends)
 >>> ranges
[(2637, 6457), (8345, 9086), (10100, 12304)]

Now you can get a list of slices of a string s with a simple list comp:
slices = [ s[begin:end] for begin, end in ranges ]

and of course the creation of ranges can be abbreviated:
 >>> first, second = zip(*data)
 >>> ranges = zip(second[:-1], first[1:])

Kent



More information about the Tutor mailing list