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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With