+ 4

the key param of sorted function, can we control what it does if 2 elements have same value used to sort the iterable?

Like if the iterable is a list of tuples: L = [(0, 2), (1, 3), (1, 2), (-1, 2)] And when we do print(sorted(L, key = lambda t: t[1])) it sorts the tuple whose 2nd element is same based on their index in the original list. What if I want to sort the elements whose 2nd value (in this case) is same based on their 1st value? Like (0, 2) and (1, 2) and (-1, 2) should be sorted as (-1, 2), (0, 2), (1, 2)

21st Mar 2019, 5:05 PM
Yash✳️
Yash✳️ - avatar
1 Respuesta
+ 5
In the key lambda, you can use any function or expression to determine the ordering of elements. Sorting by multiple keys is possible if you define a tuple in the lambda like this: print(sorted(L, key = lambda t: (t[1], t[0]))) In this case the second key is the first element of the original tuples.
21st Mar 2019, 9:25 PM
Tibor Santa
Tibor Santa - avatar