Hi all,

I want to take this code:

list_in_list = [[1,5,13,30,-4], [1,5,10,30,-4], [1,5,15,30,-4], [1,5,9,30,-4], [1,5,16,30,-8]]

and sort it by the 3rd item in each sublist (list_in_list[x][2])

I'd like to do it by the highest number so my output would be:

sorted_list_in_list = [[1,5,16,30,-8],[1,5,15,30,-4], [1,5,13,30,-4],[1,5,10,30,-4], [1,5,9,30,-4]]

Any help or suggestions?

It's difficult for me to translate the tuple and dictionary code to a simple list. Can anyone help explain it to me with my code?

Figured it out:

import operator

myreturn = operator.itemgetter(2)

list_in_list = [[1,5,13,30,-4], [1,5,10,30,-4], [1,5,15,30,-4], [1,5,9,30,-4], [1,5,16,30,-8]]

list_in_list.sort(key=myreturn, reverse=True)

print list_in_list

As you most likely found out, there are a number of ways to do this. You picked a good one.

There was also a snippet at:
http://www.daniweb.com/code/snippet237089.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.