Q:

Is there a more concise way to create pairs from a python list?

I have a list where x[0][0] = position of x[0][1] in a string S.
x  = [[157, 'Start_Summary'], [1228, 'End_Summary'], [1233, 'Start_Skills'], [1540, 'End_Skills'], [1925, 'Start_Work'], [2392, 'profile_start'], [4378, 'profile_end'], [4451, 'profile_start'], [5368, 'profile_end'], [5759, 'profile_start'], [7000, 'profile_end'], [7000, 'End_Work']]

I want to create a list of tuples such that the output list would be pairs of positions of Start and End of a particular type of tag - 
y = [(157,1228),(1233,1540),(1925,7000),(2392,4378),(4451,5368),(5759,7000)]

I have tried using for loop and if-else statements, but I am looking for a pythonic way to generate such a list.

A:

you can store your data in a collections.defaultdic:
from collections import defaultdict

data = defaultdict(list)

positions = {'start', 'end'}
for n, s in x:
    p, t = s.lower().split('_')
    if p not in positions:
        p, t = t, p
    data[t].append(n)

[tuple(v[i: i + 2] ) for v in data.values() for i in range(0, len(v)-1, 2)]

output:
[(157, 1228),
 (1233, 1540),
 (1925, 7000),
 (2392, 4378),
 (4451, 5368),
 (5759, 7000)]

