Below is a code to generate the products of any two 3-digits numbers
integers_list = [(i * x) for i in range(100,1000) for x in range(100,1000)]
string_list = (map(str, integers_list))
integers_list.sort()
string_list.sort()
print integers_list[-10:-1]
print string_list[-10:-1]
gives:
[995004, 995004, 995006, 995006, 996003, 996003, 996004, 997002, 997002]
['99994', '99994', '99996', '99996', '99997', '99997', '99999', '99999', '99999']
This also occurs if I instead use str(i * x) in the list comprehension.
The numbers in the strings list aren't even possible given the expression.
Why is this happening, and what can I do to fix it?
Strings sort in a different order than integers. 9800 is greater than 990, but '9800' is less than '990'.
As Mark Ransom pointed out, the reason is because sorting strings is done lexicographically. To make the sorting process sort by integer value, do this:
string_list.sort(key=int)
integers_list.sort(key=int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With