Change language

Python | Sort the list of percentages

Let’s look at different ways to accomplish a task.

Code # 1: Breaks & # 39;% & # 39; in a string and converts it to a floating point number.

# Python code to sort the percent list

 
# Initialization list

Input = [ ’2.5%’ , ’6.4%’ , ’91.6%’ , ’11.5%’ ]

 
# remove% and convert to float
# then apply the function sorting

Input . sort (key  = lambda x: float (x [: - 1 ]))

 
# printing

print ( Input )

Exit:

 [’2.5%’, ’6.4%’, ’11.5%’, ’91.6%’] 

Code # 2:

# Python code to sort the percent list

 
# Initialization list

Input = [ ’2.5%’ , ’6.4%’ , ’ 91.6% ’ , ’ 11.5% ’ ]

 
# Temporary initialization list

temp = []

 
# remove the% sign

for key in Input :

temp.append ((key [: - 1 ]))

 
# c floating point list formatting

temp = sorted (temp, key = float )

 
# Initialize the output list

output = []

 
# Adding percent sign

for key in temp:

output.append (key + ’%’ )

 
# print output

print (output)

Exit:

 [’2.5%’, ’6.4%’, ’11.5%’, ’91.6%’] 

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method