Python – Sort List items on basis of their Digits
Last Updated :
10 Mar, 2023
Given List of elements, perform sorting on basis of digits of numbers.
Input : test_list = [434, 211, 12, 3] Output : [12, 211, 3, 434] Explanation : 3 < 12, still later in list, as initial digit, 1 < 3. Hence sorted by digits rather than number. Input : test_list = [534, 211, 12, 7] Output : [12, 211, 534, 7] Explanation : 7 < 534, still later in list, as initial digit, 5 < 7. Hence sorted by digits rather than number.
Method #1 : Using map() + str() + ljust() + sorted()
In this, the list elements are converted into string using map() and str(), ljust() is used to append constant character to make each number equal length. Then sort is performed using sorted().
Python3
test_list = [ 434 , 211 , 12 , 54 , 3 ]
print ( "The original list is : " + str (test_list))
temp1 = map ( str , test_list)
max_len = max ( map ( len , temp1))
res = sorted (test_list, key = lambda idx : ( str (idx).ljust(max_len, 'a' )))
print ( "List after sorting : " + str (res))
|
Output
The original list is : [434, 211, 12, 54, 3]
List after sorting : [12, 211, 3, 434, 54]
Time Complexity: O(nlogn) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), additional space is not needed.
Method #2 : Using list comprehension + sorted() + lambda
In this, we as parameter to sorted(), pass a list of digits. Performing sort according to that gives desired results.
Python3
test_list = [ 434 , 211 , 12 , 54 , 3 ]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = lambda ele: [ int (j) for j in str (ele)])
print ( "List after sorting : " + str (res))
|
Output
The original list is : [434, 211, 12, 54, 3]
List after sorting : [12, 211, 3, 434, 54]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...