Python | Sort a list of percentage
Given a list of percentage, write a Python program to sort the given list in ascending order. Let’s see different ways to do the task. Code #1: Chops ‘%’ in string and convert it into float.
Python3
Input = [ '2.5 %' , '6.4 %' , '91.6 %' , '11.5 %' ]
Input .sort(key = lambda x: float (x[: - 1 ]))
print ( Input )
|
Output:
['2.5 %', '6.4 %', '11.5 %', '91.6 %']
Time Complexity: O(nlogn), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Code #2:
Python3
Input = [ '2.5 %' , '6.4 %' , '91.6 %' , '11.5 %' ]
temp = []
for key in Input :
temp.append((key[: - 1 ]))
temp = sorted (temp, key = float )
output = []
for key in temp:
output.append(key + '%' )
print (output)
|
Output:
['2.5 %', '6.4 %', '11.5 %', '91.6 %']
Time Complexity: O(nlogn), where n is the length of Input list.
Auxiliary Space: O(n), where n is the number of elements in output list
Using re:
Here is another approach using the re module and a lambda function:
- Import the re module
- Define a lambda function that takes a string as input and uses a regular expression to extract the float value of the string
- Use the sorted() function to sort the input list using the lambda function as the key
Here is the implementation of this approach:
Python3
import re
def sort_percentage_list(lst):
key = lambda x: float (re.search(r "(\d+\.\d+)" , x).group())
return sorted (lst, key = key)
lst = [ '2.5 %' , '6.4 %' , '91.6 %' , '11.5 %' ]
print (sort_percentage_list(lst))
|
Output
['2.5 %', '6.4 %', '11.5 %', '91.6 %']
The regular expression r”(\d+\.\d+)” will match and extract any float value in the string. For example, it will match ‘2.5’ in the string ‘2.5 %’. The group() method of the Match object returned by re.search() will then return the matched
Time complexity: O(nlogn)
Auxiliary Space: O(1)
Last Updated :
25 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...