Python Forum

Full Version: sorting a list of lists by an element
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have a list of lists that I want to sort, something like :

data = [[0,False,'c'], [0,True,'z'], [1,False,'P'], [0,True,'A']]
I want all lists that have a True value at the top of Data, like :

sortingFuntion(data) = [[0,True,'z'], [0,True,'A'], [0,False,'c'], [1,False,'P']]
I can access the boolean with Data[i][1] in a for loop but I can't come up with how to transmit that value as a criteria to sorted()

Thanks
Use sorted with a custom key function
data = [[0, False, "c"], [0, True, "z"], [1, False, "P"], [0, True, "A"]]
sorted_data = sorted(data, key=lambda x: x[1], reverse=True)
print(sorted_data)
Output:
[[0, True, 'z'], [0, True, 'A'], [0, False, 'c'], [1, False, 'P']]

Instead of using lamda you can also use itemgetter from the operator module
from operator import itemgetter

data = [[0, False, "c"], [0, True, "z"], [1, False, "P"], [0, True, "A"]]
sorted_data = sorted(data, key=itemgetter(1), reverse=True)
print(sorted_data)
And for the folks that don't like lambdas, in this case itemgetter is possible as well.

from operator import itemgetter
[...]
sorted_data = sorted(data, key=itemgetter(1), reverse=True)
Thanks a lot !

I am fairly new to programming, will look up the lamda and itemgetter functions