Python program to list Sort by Number value in String
Last Updated :
16 May, 2023
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))
OutputThe 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))
OutputThe 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
OutputThe 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))
OutputThe 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))
OutputThe 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)
Similar Reads
Python program to Sort a List of Strings by the Number of Unique Characters
Given a list of strings. The task is to sort the list of strings by the number of unique characters. Examples: Input : test_list = ['gfg', 'best', 'for', 'geeks'], Output : ['gfg', 'for', 'best', 'geeks'] Explanation : 2, 3, 4, 4 are unique elements in lists. Input : test_list = ['gfg', 'for', 'geek
6 min read
Sort Numeric Strings in a List - Python
We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
2 min read
Python program to find smallest number in a list
In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function. Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value. [GFGTABS]
3 min read
Python Program to Sort a String
Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least. Using sorted with join()sorted() functio
2 min read
Sort given list of strings by part the numeric part of string - Python
We are given a list of strings containing both letters and numbers, and the goal is to sort them based on the numeric part within each string. To do this, we extract the digits, convert them to integers and use them as sorting keys. For example, in ["Gfg34", "is67", "be3st"], the numbers 34, 67, and
3 min read
How to sort a list of strings in Python
In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort(). Using sort() MethodThe sort() method sorts a list in place and modifying the original list directly. [GFGTABS] Python a = ["banana", "apple", "cher
2 min read
Python program to Sort a List of Dictionaries by the Sum of their Values
Given Dictionary List, sort by summation of their values. Input : test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 100}, {8 : 9, 7 : 3}] Output : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 100}] Explanation : 12 < 13 < 100, sorted by values sum Input : test_list = [{1 : 100}, {8 : 9, 7 : 3}] Output : [{8:
6 min read
Python - Sort list of numbers by sum of their digits
Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case. Using sorted() with a Lambda Functionsorted() function
2 min read
Python | Sort given list of strings by part of string
We are given with a list of strings, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string. Using sort() with lambda functionThis
3 min read
Python - Sort Strings by Maximum ASCII value
Given strings list, perform sort by Maximum Character in String. Input : test_list = ["geeksforgeeks", "is", "best", "cs"] Output : ["geeksforgeeks", "is", "cs", "best"] Explanation : s = s = s < t, sorted by maximum character. Input : test_list = ["apple", "is", "fruit"] Output : ["apple", "is",
4 min read