Python randomly sorts items of the same value

This is a bit complicated, and I could not come up with anything succinct.

I have a list of tuples sorted by tuple element. It is possible that these elements have the same meaning, 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 1 and 2 in their own sets. This should replace the mysql bit:

 ORDER BY num_of_hotdogs DESC, rand() 
+7
source share
1 answer

You can sort the elements by a tuple consisting of yourself, and then a random number. If v_1 < v_2 , (v_1, random.random()) < (v_2, random.random()) ; if v_1 == v_2 , it will return to random number comparison.

 sorted(a, key=lambda v: (v, random.random())) 
+8
source

All Articles