SoFunction
Updated on 2024-11-12

Python Sorting by Multiple Conditions

Sort the tuples, first in ascending order by the first element, then in descending order by the second element if the first element is the same.

L = [(12, 12), (34, 13), (32, 15), (12, 24), (32, 64), (32, 11)]
(key=lambda x: (x[0], -x[1]))
print(L)

Results:

[(12, 24), (12, 12), (32, 64), (32, 15), (32, 11), (34, 13)]

Above this python sorting according to multiple conditions is all I have shared with you, I hope to give you a reference, and I hope you support me more.