How to sort an array of strings where each string represents a decimal number in Python

1 Answer

0 votes
# Import required module for sorting
import functools

# Comparator function to sort strings as decimal numbers
def compare_as_decimal(a, b):
    # Convert strings to float for comparison
    num_a = float(a)
    num_b = float(b)
    return (num_a > num_b) - (num_a < num_b)  # Equivalent to Java's Double.compare

# Input list of strings
numbers = ["12.3", "5.6", "789.1", "3.14", "456.0", "0", "0.01", "4.0"]

# Sort the list using the custom comparator
numbers.sort(key=functools.cmp_to_key(compare_as_decimal))

print("Sorted list of decimal strings:")
for num in numbers:
    print(num, end="  ")




"""
run:

Sorted list of decimal strings:
0  0.01  3.14  4.0  5.6  12.3  456.0  789.1

"""

 



answered Sep 1, 2025 by avibootz
...