Skip to content Skip to sidebar Skip to footer

Python: List.sort() Doesn't Seem To Work

>>> x = set(['216', '217', '214', '215', '212', '213', '210', '211', '165', '264', '218', '219', '133', '132', '131', '130', '137', '136', '135', '226', '139', '138', '166

Solution 1:

If you want to sort them as ints, i.e. numerically, not lexicographically, use y = sorted(x, key=int).

Solution 2:

Because these are strings you are sorting e.g '1','2' and '100', they are ordered by the bytes that make up the string.. not the number the string represents.

Because the bytes that represent the character '1' is less that the byte that represents the character '2', all the strings starting with '1' will be first. etc etc.

You need do convert the strings to integers and then sort them to make them sort in numerical order.

G./

Post a Comment for "Python: List.sort() Doesn't Seem To Work"