Home > OS >  How to sort an array of array by element closest to 0
How to sort an array of array by element closest to 0

Time:11-21

I have an array of integer arrays like:

i = [[1,3,8],[1,7,4],[1,9,1],[1,0,3],[1,11,-2]]

And I want a result like:

i = [[1,9,1],[1,11,-2],[1,0,3],[1,7,4],[1,3,8]]

where the "i" array is sorted in a way that i[x][2] is closest to 0.

I tried to change the lambda in: sorted_i = sorted(i, key=lambda x: x[2]) but with no success.

CodePudding user response:

What you want is:

sorted_i = sorted(i, key=lambda x: abs(x[2]))

Which compares the absolute values (converts negatives to positives).

CodePudding user response:

You could also do If ... Else in One Line x[2] if x[2] > 0 else -x[2]

arr = [[1, 3, 8], [1, 7, 4], [1, 9, 1], [1, 0, 3], [1, 11, -2]]
sorted_arr = sorted(arr, key=lambda x: x[2] if x[2] > 0 else -x[2])
print(sorted_arr) #[[1, 9, 1], [1, 11, -2], [1, 0, 3], [1, 7, 4], [1, 3, 8]]
  • Related