Open In App

Python program to list Sort by Number value in String

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list.

Input : test_list = [“gfg is 4”, “all no 1”, “geeks over 7 seas”, “and 100 planets”] 
Output : [‘all no 1’, ‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’] 
Explanation : 1 < 4 < 7 < 100, numbers in strings deciding order.

Input : test_list = [“gfg is 4”, “geeks over 7 seas”, “and 100 planets”] 
Output : [‘gfg is 4’, ‘geeks over 7 seas’, ‘and 100 planets’] 
Explanation : 4 < 7 < 100, numbers in strings deciding order. 

Method 1 : Using sort(), split() and isdigit()

In this, we perform the task of in-place sorting using sort(), and perform task of getting number from string using split() and final detection is done using isdigit(). 

Example: 

Python3




import sys
 
def num_sort(strn):
 
    # getting number using isdigit() and split()
    computed_num = [ele for ele in strn.split() if ele.isdigit()]
 
    # assigning lowest weightage to strings
    # with no numbers
    if len(computed_num) > 0:
        return int(computed_num[0])
    return -1
 
 
# initializing Matrix
test_list = ["gfg is", "all no 7", "geeks over seas", "and planets 5"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort
test_list.sort(key=num_sort)
 
# printing result
print("Sorted Strings : " + str(test_list))


Output

The original list is : ['gfg is', 'all no 7', 'geeks over seas', 'and planets 5']
Sorted Strings : ['gfg is', 'geeks over seas', 'and planets 5', 'all no 7']

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Method 2 : Using sorted(), lambda,  split() and isdigit()

In this, lambda function is used to inject sort functionality performed using sorted(). Rest each process is similar to above explained method.

Example:

Python3




# initializing Matrix
test_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sorting
# lambda function injecting functionality
res = sorted(test_list, key=lambda strn: -1
             if len([ele for ele in strn.split()
                     if ele.isdigit()]) == 0
             else int([ele for ele in strn.split()
                       if ele.isdigit()][0]))
 
# printing result
print("Sorted Strings : " + str(res))


Output

The original list is : ['all no 100', 'gfg is', 'geeks over seas 62', 'and planets 3']
Sorted Strings : ['gfg is', 'and planets 3', 'geeks over seas 62', 'all no 100']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: Using regular expression

In this, we use regular expression to form pattern and match the pattern against each string. Then we can use sort() for sorting the strings by their number values.

Python3




import re
 
# initializing Matrix
test_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"]
  
# printing original list
print("The original list is : " + str(test_list))
 
# performing sorting
# using regular expression
res = sorted(test_list, key=lambda s: int(re.search('\d+', s).group()) if re.search('\d+', s) else 0)
  
# printing result
print("Sorted Strings : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : ['all no 100', 'gfg is', 'geeks over seas 62', 'and planets 3']
Sorted Strings : ['gfg is', 'and planets 3', 'geeks over seas 62', 'all no 100']

Time Complexity: O(n)
Auxiliary Space: O(n)  

Method 4: Using a for loop and string manipulation.

Step-by-step approach:

  • Initialize an empty list “digit_indices” to store the indices of the digits in each element.
  • Iterate through each element in the list “test_list”.
  • Initialize an empty list “indices” to store the indices of the digits in the current element.
  • Iterate through each character in the current element using a for loop.
  • If the character is a digit, append its index to the “indices” list.
  • After the for loop, append the “indices” list to the “digit_indices” list.
  • Use the “digit_indices” list to sort the original list “test_list”.
  • Print the sorted list.

Python3




# Initializing Matrix
test_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sorting based on presence of digits
digit_indices = []
for elem in test_list:
    indices = []
    for i in range(len(elem)):
        if elem[i].isdigit():
            indices.append(i)
    digit_indices.append(indices)
res = [x for _, x in sorted(zip(digit_indices, test_list))]
 
# printing result
print("Sorted Strings : " + str(res))


Output

The original list is : ['all no 100', 'gfg is', 'geeks over seas 62', 'and planets 3']
Sorted Strings : ['gfg is', 'all no 100', 'and planets 3', 'geeks over seas 62']

Time complexity: O(n^2), where n is the length of the longest element in the list. 
Auxiliary space: O(n), where n is the length of the list. 

Method 5: Using a custom comparison function

Step-by-step approach:

  • Import the cmp_to_key function from the functools module. This function is used to convert a comparison function to a key function.
  • Define a function named compare_strings that takes two strings as arguments and returns the result of their comparison based on the number of digits and their values present in them. The function extracts the digits from the strings using the split() and isdigit() methods and then compares them. If the strings have the same number of digits, it compares their values. If one string has more digits than the other, it is considered greater.
  • Use the sorted() function to sort the test_list based on the results of the compare_strings() function. The key argument of the sorted() function specifies that the compare_strings() function should be used to sort the list.
  • Print the sorted list.

Python3




# Importing the cmp_to_key function from the functools module
from functools import cmp_to_key
 
# Initializing Matrix
test_list = ["all no 100", "gfg is", "geeks over seas 62", "and planets 3"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sorting based on presence of digits
def compare_strings(s1, s2):
    s1_digits = [int(s) for s in s1.split() if s.isdigit()]
    s2_digits = [int(s) for s in s2.split() if s.isdigit()]
    if len(s1_digits) == len(s2_digits):
        for i in range(len(s1_digits)):
            if s1_digits[i] != s2_digits[i]:
                return s1_digits[i] - s2_digits[i]
    else:
        return len(s1_digits) - len(s2_digits)
    return 0
 
res = sorted(test_list, key=cmp_to_key(compare_strings))
 
# printing result
print("Sorted Strings : " + str(res))


Output

The original list is : ['all no 100', 'gfg is', 'geeks over seas 62', 'and planets 3']
Sorted Strings : ['gfg is', 'and planets 3', 'geeks over seas 62', 'all no 100']

Time complexity: O(n log n)
Auxiliary space: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads