Numerical Sorting of String Lists in Python
Attempting to numerically sort a list of strings in Python using the sort() function can result in unexpected outcomes. The default sorting algorithm for strings in Python is often alphabetical rather than numerical.
To sort a list of strings numerically, the strings must first be converted to integers. However, the provided code snippet attempts to convert the strings to integers but does not utilize the converted values for sorting.
The correct approach is to convert the strings to integers using a list comprehension:
list1 = ["1", "10", "3", "22", "23", "4", "2", "200"] list1 = [int(x) for x in list1]
Once the strings are converted to integers, the list can be sorted using the sort() function:
list1.sort()
This will result in the list being sorted in ascending numerical order.
Alternatively, if it is necessary to keep the elements as strings, a key function can be used to specify the comparison criteria. The key function is called on each element before it is compared, and the return values are used for comparison instead of the elements themselves:
list1.sort(key=int)
This will also sort the list numerically, but the elements will remain as strings.
The above is the detailed content of How to Numerically Sort a List of Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!