Python – Sort given list of strings by part the numeric part of string

PythonServer Side ProgrammingProgramming

When it is required to sort a given list of strings based on a numeric part of the string, a method is defined that uses the regular expressions, the ‘map’ method and the ‘list’ method to display the result.

Example

Below is a demonstration of the same −

import re
print("The regular expression package has been imported successfully.")

def my_digit_sort(my_list):
   return list(map(int, re.findall(r'\d+', my_list)))[0]

my_list = ["pyt23hon", "fu30n", "lea14rn", 'co00l', 'ob8uje3345t']

print("The list is : " )
print(my_list)

my_list.sort(key=my_digit_sort)
print("The list has been sorted based on the pre-defined method..")

print("The resultant list is : ")
print(my_list)

Output

The regular expression package has been imported successfully.
The list is :
['pyt23hon', 'fu30n', 'lea14rn', 'co00l', 'ob8uje3345t']
The list has been sorted based on the pre-defined method..
The resultant list is :
['co00l', 'ob8uje3345t', 'lea14rn', 'pyt23hon', 'fu30n']

Explanation

  • The required packages are imported into the environment.

  • A method named 'my_digit_sort' is defined and it takes a list as a paramater.

  • It uses the regular expression and the 'findall' method of the 're' package to find the digits present inside the words.

  • This is mapped to all elements in the list.

  • This is converted into a list and is returned as output.

  • Outside the method, a list of strings that contains integers is defined and displayed on the console.

  • This list is sorted based on the pre-defined method.

  • This output is displayed on the console.

raja
Published on 13-Sep-2021 07:49:18
Advertisements