[Tutor] List manipulation

Kent Johnson kent37 at tds.net
Thu Sep 14 11:51:05 CEST 2006


Srinivas Iyyer wrote:
> Thank you Bob for your email.
> Sorry for the confusion. 
> here is what I ment:
> 
> test = ['10\t15', '16\t20', '25\t35', '45\t50',
> '55\t60', '61\t65', '75\t80']

>>> I would get:
>>> 10      20
>>> 25      35
>>> 45      50
>>> 55      65
>>> 75      80

Here is my take on it:

test = ['10\t15', '16\t20', '25\t35', '45\t50','55\t60', '61\t65', '75\t80']

pairs = [ map(int, x.split('\t')) for x in test ]

i = iter(pairs)

last = i.next()

for current in i:
     if current[0] == last[1]+1:
         last = [last[0], current[1]]
     else:
         print last
         last = current

print last


You can also wrap this in a generator which yields the desired pairs, so 
they can be printed or put in a list or whatever:

def compress(pairs):
     i = iter(pairs)

     last = i.next()

     for current in i:
         if current[0] == last[1]+1:
             last = [last[0], current[1]]
         else:
             yield last
             last = current

     yield last


for pair in compress(pairs):
     print pair


Kent



More information about the Tutor mailing list