Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python randomly sort items of the same value

Tags:

python

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()
like image 617
Matt Avatar asked May 16 '12 20:05

Matt


1 Answers

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()))
like image 173
Danica Avatar answered Oct 20 '22 07:10

Danica