sorting a list in python
Question: I am trying to sort lists on a list : each list contains `[seq1,seq2,score]` ,
I want to sort the list `L` according to the score of (seq1,seq2) from the max
score to the minimum score, then each list take a rank to each (seq1,seq2)
according to the score

    
    
    L=[ ['AA', 'CG', 0],['AA', 'AA', 4], ['CG', '--', -1]]
    

the sorted list must be:

    
    
    L=[['AA', 'AA', 4], ['AA', 'CG', 0], ['CG', '--', -1]]
    

for the ranks:

    
    
    ['AA', 'AA', 4] has rank 1
    ['AA', 'CG', 0] has rank 2
    ['CG', '--', -1] has rank 3
    

how can I do it? I tried:

    
    
    def getKey():/* to get the score from each list*/
        scorelist=score()/*this is the list L*/
        return scorelist[][2]
    
    
    
    def sort_list():
       scorelist=score()
        p=sorted(s, key=getKey)
        return p
    


Answer: You can use
[`itemgetter`](https://docs.python.org/3.4/library/operator.html?highlight=itemgetter#operator.itemgetter)
as a function to get the value to sort the list by. Then to get the rank, you
can use
[`enumerate`](https://docs.python.org/3.4/library/functions.html#enumerate).

    
    
    from operator import itemgetter
    
    score_list = score()
    score_list.sort(key=itemgetter(2), reversed=True) # sort list descending by third element
    for i, values in enumerate(score_list):
        print(values, i+1) # print values and rank
    

If several items can share the same score, you can use
[groupby](https://docs.python.org/3.4/library/itertools.html?highlight=groupby#itertools.groupby)
to assign them the same rank:

    
    
    from operator import itemgetter
    from itertools import groupby
    
    score_list = score()
    score_list.sort(key=itemgetter(2), reversed=True)
    for i, group in enumerate(groupby(score_list)):
        for item in group:
            print(item, i+1)
    

With this code, if you have 2 items ranked first, the next item will be ranked
second. If you want to rank it third (as expected), you can increment the rank
in the inner loop (and save it rank for display):

    
    
    from operator import itemgetter
    from itertools import groupby
    
    score_list = score()
    score_list.sort(key=itemgetter(2), reversed=True)
    rank = 1 # counter for the rank
    for group in groupby(score_list):
        current_rank = rank # save the rank
        for item in group:
            print(item, current_rank)
            rank += 1 # rank increment in inner loop
    

