-1

My question is i have inp=[1,52,234,65,87,57,96,0,3] and output should be output=[0,1,52,3,234,65,96,87,57]. if the last digit is the same you leave them in same order as they are on input.increasing.

inp=[1,52,234,65,87,57,96,0,3]
output=[0,1,52,3,234,65,96,87,57]

how you sort integers on last digit?

DYZ
  • 55,249
  • 10
  • 64
  • 93
  • Possible duplicate of [Sort array of objects by string property value in JavaScript](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – ThoFin Sep 15 '18 at 04:47

3 Answers3

5

You can sort using a key function that calculates n%10:

sorted(inp, key=lambda n: n%10)

or

sorted(inp, key=(10).__rmod__)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

The last digit of a number is the remainder of division by 10:

sorted(inp, key=lambda x: x % 10)
#[0, 1, 52, 3, 234, 65, 96, 87, 57]
DYZ
  • 55,249
  • 10
  • 64
  • 93
0

You can use the sorted() built in with the keyword argument key:

sort = sorted(inp,
              key=lambda x: str(x)[-1])

This takes the value, converts it to a string to get the -1 index from it, then that value is able to be compared and sorted. You don't need to cast it back into an integer.

N Chauhan
  • 3,407
  • 2
  • 7
  • 21