Tuesday, June 9, 2020

How to sort a list based on element's position

Let's say there is a list of numbers

data = [9,10,15,51,68,85,19]

Sort the list based on the number in the units place. So, here sort the data based on the second digit and output should be

[10, 51, 15, 85, 68, 9, 19]

Remember single digits has 0 prepended internally. We can do it with a single line using lambda and built in sort function of list

sorted(data, key=lambda x: x%10)

This works well for numerics. What if the list has a combination of strings and numerics or strings? In this case we want to convert everything into a string and sort based on the index of string required. In this example as we are looking at second digit/ letter, index will be 1 (remember indexes start with 0)

sorted(data, key=lambda x: str(x)[1] if len(str(x))>1 else str(x)[0])


No comments: