best method and data structure for sorting a list of tuples into multiple lists?
Question: Let's say I have a list of tuples like this:

    
    
    l = [('music','300','url'),('movie','400','url'),
    ('clothing','250','url'),('music','350','url'),
    ('music','400','url'),('movie','1000','url')]
    

and that I want to sort these tuples into multiple lists, each grouped by the
first element in the tuples. Further, once grouped into those lists, I want
the new lists reverse sorted by the second element (the int). So, the result
would be:

    
    
    music = [('music','400','url'),('music','350','url'),('music','300','url')]
    movie = [('movie','1000','url'),('movie','400','url')]
    clothing = [('clothing','250','url')]
    

Perhaps I could forego the multiple lists and make a list of lists of tuples?
So, I would get:

    
    
    sortedlist = [[('music','400','url'),('music','350','url'),('music','300','url')],
    [('movie','1000','url'),('movie','400','url')],
    [('clothing','250','url')]]
    

But even in this case, how would I get the internal lists reverse sorted by
the second element?

If I'm going about this the wrong way, please mention it. I'm still new at
Python. Thx!


Answer: You can do something like this:

    
    
    import itertools
    import operator
    
    sorted_l = sorted(l, key=lambda x: (x[0], int(x[1])), reverse=True)
    
    print [list(g[1]) for g in itertools.groupby(sorted_l, key=operator.itemgetter(0))]
    

Output :

    
    
    [[('music', '400', 'url'), ('music', '350', 'url'), ('music', '300', 'url')],
     [('movie', '1000', 'url'), ('movie', '400', 'url')],
     [('clothing', '250', 'url')]]
    

