1

I have a sorted list such as

[[1, 'start'], [13, 'start'], [13, 'end'], [15, 'end']]

which is the output of my_list.sort(key=lambda x: x[0]). However, if there is a tie with the 0th element of each sub-list, as is the case with the middle two elements, then I need the sort to have the lists with end come first. So the desired output would be

[[1, 'start'], [13, 'end'], [13, 'start'], [15, 'end']]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

2 Answers2

1

You can do it sorting by another element, a boolean, indicating whether or not the second element is end:

my_list.sort(key=lambda x: (x[0], x[1] != 'end'))
[[1, 'start'], [13, 'end'], [13, 'start'], [15, 'end']]

This will be using the following list of tuples in order to sort the list:

[(x[0], x[1] != 'end') for x in my_list]
[(1, True), (13, True), (13, False), (15, False)]

Where the second element will be False if it is not end in my_list. Now sorting this array will yield the expected result, given that False i.e. (0) will come before True (1) when the first elements match:

sorted([(x[0], x[1] != 'end') for x in my_list])
[(1, True), (13, False), (13, True), (15, False)]

As @jpp points out you could simply sort by the second element lexicographically in this case:

my_list.sort()
[[1, 'start'], [13, 'end'], [13, 'start'], [15, 'end']]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
yatu
  • 86,083
  • 12
  • 84
  • 139
0

try this

my_list.sort(key = lambda x:(x[0],x[1]))
jamil
  • 26
  • 6