This is a bit tricky and I couldn't come up with anything concise.
I have a list of tuples sorted by an item of the tuple. It's possible for these items to have the same value, so something like this:
a = [(a,1), (b,1), (c, 1), (d,2), (e,2), (f,2)]
What I'm looking for, is a way to randomize the order of all the 1's and 2's within their own sets. This is to replace a bit of mysql:
ORDER BY num_of_hotdogs DESC, rand()
You could sort items by a tuple consisting of themselves and then a random number. If v_1 < v_2
, (v_1, random.random()) < (v_2, random.random())
; if v_1 == v_2
, it'll fall back to comparing on the random number.
sorted(a, key=lambda v: (v, random.random()))
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