Python | Sort Numerical Records in String
Last Updated :
24 Mar, 2023
Sometimes, while working with Python records we can have a problem that they may occur in name and number format in strings. These may be required to be sorted. This problem can occur in many domains in which data is involved. Let us discuss certain ways in which this task can be performed.
Method #1 : Using join() + split() + sorted() + list comprehension
The combination of above functions can be used to perform this task. In this, we perform the task of sort using sorted(), and task of extracting numbers using split(). We perform the task of rejoining sorted string using join().
Python3
# Python3 code to demonstrate working of
# Sort Numerical Records in String
# Using join() + split() + sorted() + list comprehension
# initializing string
test_str = "Akshat 15 Nikhil 20 Akash 10"
# printing original string
print("The original string is : " + test_str)
# Sort Numerical Records in String
# Using join() + split() + sorted() + list comprehension
temp1 = test_str.split()
temp2 = [temp1[idx: idx + 2] for idx in range(0, len(temp1), 2)]
temp3 = sorted(temp2, key=lambda ele: (int(ele[1]), ele[0]))
res = ' '.join([' '.join(ele) for ele in temp3])
# printing result
print("The string after sorting records : " + res)
Output : The original string is : Akshat 15 Nikhil 20 Akash 10
The string after sorting records : Akash 10 Akshat 15 Nikhil 20
Time complexity: O(n log n) where n is the number of records in the string.
Auxiliary space complexity: O(n) where n is the number of records in the string.
Method #2: Using regex
This task can also be performed using regex. We perform the task of finding numbers using regex and rest of sorting and joining is performed as the above method.
Python3
# Python3 code to demonstrate working of
# Sort Numerical Records in String
# Using regex
import re
# initializing string
test_str = "Akshat 15 Nikhil 20 Akash 10"
# printing original string
print("The original string is : " + test_str)
# Sort Numerical Records in String
# Using regex
temp1 = re.findall(r'([A-z]+) (\d+)', test_str)
temp2 = sorted(temp1, key=lambda ele: (int(ele[1]), ele[0]))
res = ' '.join(' '.join(ele) for ele in temp2)
# printing result
print("The string after sorting records : " + res)
OutputThe original string is : Akshat 15 Nikhil 20 Akash 10
The string after sorting records : Akash 10 Akshat 15 Nikhil 20
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using dictionaries
Use dictionaries to store the name and corresponding numerical value as key-value pairs, and then sort the dictionary based on the numerical value. Finally, you can combine the sorted keys and values to form the sorted string.
Python3
# initializing string
test_str = "Akshat 15 Nikhil 20 Akash 10"
# printing original string
print("The original string is : " + test_str)
# Sort Numerical Records in String
# Using dictionaries
temp1 = test_str.split()
temp2 = {}
for i in range(0, len(temp1), 2):
temp2[temp1[i]] = int(temp1[i+1])
temp3 = sorted(temp2.items(), key=lambda ele: ele[1])
res = ' '.join([k + ' ' + str(v) for k, v in temp3])
# printing result
print("The string after sorting records : " + res)
OutputThe original string is : Akshat 15 Nikhil 20 Akash 10
The string after sorting records : Akash 10 Akshat 15 Nikhil 20
Time complexity: O(n log n), where n is the number of name-numerical pairs in the input string.
Auxiliary space: O(n), where n is the number of name-numerical pairs in the input string.
Method #4: Using list manipulation
program takes a string of records as input, sorts the numerical records based on the values, and returns the sorted string of records as output using list manipulation techniques such as splitting the string, mapping, sorting, and joining. The original string and the sorted string are printed as output.
- Split the string into a list of words using the split() method.
- Convert the even-indexed elements (i.e., names) into a list of strings and the odd-indexed elements (i.e., numbers) into a list of integers using list slicing and the map() function.
- Combine the two lists into a list of tuples using the zip() function.
- Sort the list of tuples by the second element (i.e., the number) using the sorted() function with a lambda function as the key.
- Combine the list of tuples into a string using a list comprehension and the join() method.
Python3
# initializing string
test_str = "Akshat 15 Nikhil 20 Akash 10"
# printing original string
print("The original string is : " + test_str)
# Sort Numerical Records in String
# Using list manipulation
temp = test_str.split()
temp[1::2] = map(int, temp[1::2])
temp = sorted(zip(temp[1::2], temp[::2]))
res = ' '.join([x[1] + ' ' + str(x[0]) for x in temp])
# printing result
print("The string after sorting records : " + res)
OutputThe original string is : Akshat 15 Nikhil 20 Akash 10
The string after sorting records : Akash 10 Akshat 15 Nikhil 20
The time complexity of the given code is O(n log n), where n is the number of records in the input string.
The space complexity of the code is O(n), where n is the number of records in the input string.
Method #6: Using lambda function and sorted()
Here is an approach that uses lambda function with sorted() to sort the numerical records in the given string.
Steps:
- Split the string into words using the split() method and store the result in a list.
- Convert the numerical values in the list to integers using map() and lambda function.
- Sort the list of tuples with the help of sorted() function and lambda function.
- Join the words in the list using join() method to get the desired output string.
Python3
# initializing string
test_str = "Akshat 15 Nikhil 20 Akash 10"
# printing original string
print("The original string is : " + test_str)
# Sort Numerical Records in String
# Using lambda function and sorted()
temp = test_str.split()
temp[1::2] = map(int, temp[1::2])
temp = sorted(zip(temp[::2], temp[1::2]), key=lambda x: x[1])
res = ' '.join([x[0] + ' ' + str(x[1]) for x in temp])
# printing result
print("The string after sorting records : " + res)
OutputThe original string is : Akshat 15 Nikhil 20 Akash 10
The string after sorting records : Akash 10 Akshat 15 Nikhil 20
Time complexity: O(n log n)
Auxiliary space: O(n)
Similar Reads
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
Reverse Sort a String - Python The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string "geeksforgeeks", the characters will be sorted from highest to lowest, resulting in a new string like "ssrokkggfeeeee". Let's understand different methods to pe
2 min read
Python - Descending Sort String Numbers Reverse Sorting a list is easy task and has been dealt with in many situations. With Machine Learning and Data Science emerging, sometimes we can get the data in the format of list of numbers but with string as data type. Generic Sort functions give erroneous result in that case, hence several other
2 min read
Python - Sort by Rear Character in Strings List Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks',
5 min read
Python - Extract Sorted Strings Given a String List, extract all sorted strings. Input : test_list = ["hint", "geeks", "fins", "Gfg"] Output : ['hint', 'fins', 'Gfg'] Explanation : Strings in increasing order of characters are extracted.Input : test_list = ["hint", "geeks", "Gfg"] Output : ['hint', 'Gfg'] Explanation : Strings in
5 min read