Merging duplicate lists and deleting a field in each list depending on the value in Python
Question: I am still a beginner in Python. I have a tuple to be filtered, merged and
sorted. The tuple looks like this:

    
    
            id, ts,val            
    tup = [(213,5,10.0),
           (214,5,20.0),
           (215,5,30.0),
           (313,5,60.0),
           (314,5,70.0),
           (315,5,80.0),
           (213,10,11.0),
           (214,10,21.0),
           (215,10,31.0),
           (313,10,61.0),
           (314,10,71.0),
           (315,10,81.0),
           (315,15,12.0),
           (314,15,22.0),
           (215,15,32.0),
           (313,15,62.0),
           (214,15,72.0),
           (213,15,82.0]  and so on
    

Description about the list: The first column(id)can have only these 6 values
213,214,215,313,314,315 but in any different order. The second column(ts) will
have same values for every 6 rows. Third column(val) will have some random
floating point values

Now my final result should be something like this:

    
    
    result = [(5,10.0,20.0,30.0,60.0,70.0,80.0),
              (10,11.0,21.0,31.0,61.0,71.0,81.0),
              (15,82.0,72.0,32.0,62.0,22.0,12.0)]
    

That is the first column in each row is to be deleted. There should be only
one unique row for each unique value in the second column. so the order of
each result row should be:

    
    
    (ts,val corresponding to id 213,val corresponding to 214, corresponding to id 215,val corresponding to 313,corresponding to id 314,val corresponding to 315)
    

Note : I am restricted to use only the standard python libraries. So panda,
numpy cannot be used.

I tried a lot of possibilities but couldnt solve it. Please help me do this.
Thanks in advance.


Answer: You can use
[itertools.groupby](https://docs.python.org/2/library/itertools.html#itertools.groupby)

    
    
    from itertools import groupby
    
    result=[]
    for i,g in groupby(lst, lambda x:x[1]):
        group= [i]+map(lambda x:x[-1],sorted(list(g),key=lambda x:x[0]))
        result.append(tuple(group))
    
    print result
    

Output:

    
    
    [(5, 10.0, 20.0, 30.0, 60.0, 70.0, 80.0), 
    (10, 11.0, 21.0, 31.0, 61.0, 71.0, 81.0), 
    (15, 82.0, 72.0, 32.0, 62.0, 22.0, 12.0)]
    

