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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read