I have a list of integers.
What I would like to do is to sort them and remove all duplicates. I saw two different solutions on the internet. Both seem to give the same result which is not the one I expect.
a = integer_combinations(5, 5)
print a
>>[4, 8, 16, 32, 9, 27, 81, 243, 16, 64, 256, 1024, 25, 125, 625, 3125]
b = sorted(a)
print b
>>[4, 8, 9, 16, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
c = dict().fromkeys(sorted(a)).keys()
print c
>> [32, 64, 4, 1024, 625, 8, 9, 256, 16, 81, 243, 3125, 25, 27, 125]
Another method, using sets:
d = list(set(b))
print d
>> [32, 64, 4, 1024, 625, 8, 9, 256, 16, 81, 243, 3125, 25, 27, 125]
What I expect is :
>>[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
Would someone know the reason of this behaviour?
Thanks!
Here is what I would use:
>>> a = [4, 8, 16, 32, 9, 27, 81, 243, 16, 64, 256, 1024, 25, 125, 625, 3125]
>>> sorted(set(a))
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
The reason your code doesn't work as expected is that dict does not guarantee any particular ordering of its keys. Similarly, set has no guarantees as to the ordering of its elements.
Therefore, the sorting step has to come right at the end.
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