0

I have an list of lists, each have a String (index 0) and a Value(index 1) the string has an number in it, example

a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3]

I want to sort it based on, firstly, the value, so the higher value goes first and if there is equal value between two arrays, sort with the digit in the string, the lower digit goes first, so it would result in this:

["Test 1", 5],["Test 2", 3], ["Test 4",3],["Test 3", 1]
Xin Cheng
  • 1,432
  • 10
  • 17

2 Answers2

0

We can try doing the following 2D sort with the help of a lambda function:

a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3]]
a.sort(key=lambda row: (row[1], -int(row[0].split()[1])), reverse=True)
print(a)  # [['Test 1', 5], ['Test 2', 3], ['Test 4', 3], ['Test 3', 1]]

The sort first orders descending using row[1], which is the second integer in each sublist. In the case of ties it then sorts ascending using the text number. We negate that value to switch the sort order.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-1
  • Return a new result:
    sorted(a, key=lambda x: (-x[1], int(x[0].split()[1])))

  • Change a itself:
    a.sort(key=lambda x: (-x[1], int(x[0].split()[1])))

lambda function generates a tuple. indicates the sort function that firstly bases on the Value(index 1) with a larger go first, and if in a tie then bases on the value in String(index 0) with the smaller go first.

  • Demo:

    a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3]]
    print(sorted(a, key=lambda x: (-x[1], int(x[0].split()[1]))))
    
  • Output:

    [['Test 1', 5], ['Test 2', 3], ['Test 4', 3], ['Test 3', 1]]
    
Xin Cheng
  • 1,432
  • 10
  • 17