Print lines with constraint in Python
Question: Suppose we have the following text file with column `a` and column `b`:

    
    
    D000001 T109
    D000001 T195
    D000002 T115
    D000002 T131
    D000003 T073
    D000004 T170
    

I wonder how to produce the following structure:

    
    
    D000001 T109 T195
    D000002 T115 T131
    D000003 T073
    D000004 T170
    

Pasted below is initial skeleton in Python.

    
    
    from __future__ import print_function
    
    with open('descr2semtype_short.txt') as f:
        for line in f:
            line = line.rstrip()
            a, b = line.split()
            print(a + ' ' + b)
    


Answer: You can use `itertools.groupby`:

    
    
    import itertools, operator
    with open('descr2semtype_short.txt') as f:
        for key, items in itertools.groupby(
            (line.rstrip().split(None,1) for line in f),
            operator.itemgetter(0)):
            print(key, ' '.join(item[1] for item in items))
    

which gives the desired output:

    
    
    D000001 T109 T195
    D000002 T115 T131
    D000003 T073
    D000004 T170
    

