Python Forum
sorting a list of lists by an element - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: sorting a list of lists by an element (/thread-34880.html)



sorting a list of lists by an element - leapcfm - Sep-10-2021

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


RE: sorting a list of lists by an element - Yoriz - Sep-10-2021

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)



RE: sorting a list of lists by an element - bowlofred - Sep-10-2021

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)



RE: sorting a list of lists by an element - leapcfm - Sep-10-2021

Thanks a lot !

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