Given a list (for instance, [1,1,2,1,2,2,3]) which is not sorted highest to lowest, and contains multiples of all numbers, I need to swap, in place, the maximums with the minimums, the second maxes with the second mins, etc. So, our example list would become [3,3,2,3,2,2,1].
Also, just to clarify, it's not just the max and min, but each layer of maxes and mins. So if the max was 4, 1's and 4's should switch as well as 2's and 3's.
I found this question on the topic: How to swap maximums with the minimums? (python)
but the code examples given seemed verbose, and assumed that there were no duplicates in the list. Is there really no better way to do this? It seems like a simple enough thing.
This is one way to do it, possible because Python is such an expressive language:
>>> a = [1,1,2,1,2,2,3]
>>> d = dict(zip(sorted(set(a)), sorted(set(a), reverse=True)))
>>> [d[x] for x in a]
[3, 3, 2, 3, 2, 2, 1]
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