nitroman
nitroman

Reputation: 673

How to sort a python list?

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

Answers (3)

user3273866
user3273866

Reputation: 604

   >> print sorted(interactions, key=lambda x: x[2])
   >> [('BRCA1', 'BRCA2', 0.2), ('TP53', 'BRCA2', 0.5), ('AGT', 'PCALM', 0.8)]

Upvotes: 0

mhlester
mhlester

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

falsetru
falsetru

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

Related Questions