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)
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']
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()
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)
or in a single line:
list1 = sorted([int(x) for x in list1])
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!