Sort complex objects by index

Here’s a quick and elegant way to sort complex objects in Python (for instance, a list of lists or a 2D array), using the objects’ indices as the key. Sorting by the second column:

Input:

data = [ [5, 7, 3],
         [4, 2, 2],
         [0, 3, 5],
       ]

Code:

data = sorted(data, key=lambda x: x[1])

The lambda keyword lets us define a mini-function which receives x (in this case, our row) and returns the second element of x (x[1]).

Output:

[[4, 2, 2],
 [0, 3, 5],
 [5, 7, 3]]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: