Home > Backend Development > Python Tutorial > How to Sort a List of String Numbers Numerically in Python?

How to Sort a List of String Numbers Numerically in Python?

Linda Hamilton
Release: 2024-12-08 17:57:12
Original
655 people have browsed it

How to Sort a List of String Numbers Numerically in Python?

Sorting a List of String Numbers Numerically

Despite its simplicity, the Python sort() function can be misleading when dealing with strings representing numbers. As demonstrated in the code snippet below, attempting to convert these strings to integers and then sort them produces incorrect results:

list1 = ["1", "10", "3", "22", "23", "4", "2", "200"]
for item in list1:
    item = int(item)

list1.sort()
print(list1)
Copy after login

Output:

['1', '10', '2', '200', '22', '23', '3', '4']
Copy after login

To rectify this issue, you must actually convert your strings to integers. Here's the corrected code:

list1 = ["1", "10", "3", "22", "23", "4", "2", "200"]
list1 = [int(x) for x in list1]
list1.sort()
Copy after login

This outputs the correct numerical order:

['1', '2', '3', '4', '10', '22', '23', '200']
Copy after login

Alternatively, if you need to keep the elements as strings, you can use the key parameter in sort(). This parameter accepts a function that is called on each element before it is compared. The key function's return value is used for comparison instead of the element itself.

For instance:

list1 = ["1", "10", "3", "22", "23", "4", "2", "200"]
list1.sort(key=int)
Copy after login

or

list1 = sorted([int(x) for x in list1])
Copy after login

The above is the detailed content of How to Sort a List of String Numbers Numerically in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template