Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list based on unit place, tens place, hundred place digit in Python

Suppose I have a list, I want to sort the digits in the following pattern:

A = [3, 30, 34, 256, 5, 9]

Sort by unit place digit first, if unit place digit is same then we will compare tens place and then hundred place. If you sort the A by this rule then:

A = [9, 5, 34, 3, 30, 256]

9 is the highest digit at Unit place 
5 is second highest
3, 34, 30 since unit digit is same here, we will compare tens place so 34 will come first here, then 3 and 30.
256 will come last since its unit place digit is 2 which is the lowest.

Suppose B = [100, 10, 1]
then after sorting B = [1, 10, 100]

Could anyone share some Pythonic way to solve this issue?

I have tried sorted(nums, key=lambda x: int(x[0]), reverse=True) but here how will I take tenth place digit into account?

Update: There is one point missing suppose A = [1, 100, 10] then in such cases after sorting A = [1, 10, 100]. In the example I gave A = [3, 30, 34, 256, 5, 9] here after sorting A = [9, 5, 34, 3, 30, 256].

Overall logic is I want to join all digits and create a largest number.

like image 880
python Avatar asked Jan 07 '23 03:01

python


1 Answers

I think you just want str as the key:

In [11]: sorted(A, key=str, reverse=True)
Out[11]: [9, 5, 34, 30, 3, 256]

Initially I read your question that you would want the reversed digits:

In [12]: sorted(A, key=lambda x: str(x)[::-1])
Out[12]: [30, 3, 34, 5, 256, 9]
like image 178
Andy Hayden Avatar answered Jan 20 '23 15:01

Andy Hayden