Reputation: 673
I have a python nested list of following format. I need to sort the list based on the third entry.
interactions = [[0 for x in xrange(3)] for x in xrange(3) ]
interactions[0] = 'TP53', 'BRCA2', 0.5
interactions[1] = 'AGT' , 'PCALM', 0.8
interactions[2] = 'BRCA1', 'BRCA2',0.2
I want to sort the list based on the third entry, means the floating point value. Please suggest one efficient method.
Upvotes: 0
Views: 135
Reputation: 604
>> print sorted(interactions, key=lambda x: x[2])
>> [('BRCA1', 'BRCA2', 0.2), ('TP53', 'BRCA2', 0.5), ('AGT', 'PCALM', 0.8)]
Upvotes: 0
Reputation: 23231
sort
has a key
argument, where you can pass in any function. In this case, make a short inline function (called a lambda) that returns the third element from your tuple:
interactions.sort(key=lambda x:x[2])
Upvotes: 1
Reputation: 369094
list.sort
or sorted
accept optional key
function. The return value of the key function is used as comparison key.
>>> interactions = [[0 for x in xrange(3)] for x in xrange(3) ]
>>> interactions[0] = 'TP53', 'BRCA2', 0.5
>>> interactions[1] = 'AGT' , 'PCALM', 0.8
>>> interactions[2] = 'BRCA1', 'BRCA2',0.2
>>> interactions.sort(key=lambda i: i[2])
>>> interactions
[('BRCA1', 'BRCA2', 0.2), ('TP53', 'BRCA2', 0.5), ('AGT', 'PCALM', 0.8)]
You can also use operator.itemgetter
in place of lambda
:
import operator
interactions.sort(key=operator.itemgetter(2))
Upvotes: 3