Home > Backend Development > Python Tutorial > How to Sort a List of Numerical Strings in Python?

How to Sort a List of Numerical Strings in Python?

Linda Hamilton
Release: 2024-12-04 20:32:17
Original
380 people have browsed it

How to Sort a List of Numerical Strings in Python?

Sorting a List of Numerical Strings

Python's sort() function can be confusing when dealing with strings representing numbers. This article explains why and presents solutions to sort such lists numerically.

The Problem:

Consider the code snippet below:

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

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

This code attempts to convert each string in the list to an integer and then sort the list. However, the output is incorrect:

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

The Solution:

The issue in the given code is that while each string is converted to an integer within the loop, the loop doesn't update the original list. To fix this, convert the strings to integers and create a new list:

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

Using a Key Function:

If you need to preserve the strings instead of converting them to integers, you can use the key parameter in the sort() function:

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

or in a single line:

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

In both cases, the int() function is called as a key on each string before comparing it, allowing the list to be sorted numerically.

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

source:php.cn
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