From: gabriele renzi Date: 2005-12-07T02:57:34+09:00 Subject: Re: Shuffling an array, sort_by{rand}'s bias (was Re: need some Ruby Uwe Schmitt ha scritto: > || > || arr.sort_by{rand} > || > that is not equivalent to my solution. > || > the python equivalent to yours is > || > arr.sort(key = lambda x: random()) > > || > || > In Python it is quite easy by using list comprehensions... > || > || What does that look like in Python? > || > > || > from random import random > || > > || > def shuffle(a): > || > b = [ (random(), i) for i in a] > || > b.sort() > || > return [ x[1] for x in b ] > || > > || > print shuffle(range(10)) > > || I would have thought those two functions do the same thing > || with the exception that shuffle does not sort in place. > || I'm probably missing something obvious. Could you explain > || the difference between the two versions? > > If you use random as sorting key, the result of a<=>b > will differ each time you evaluate a<=>b. > In my case I attach a random number to each item, > then I sort my list according to this number and remove > this 'decoration' afterwards. > > Pythonprogrammers call this pattern "decorate-sort-undecorate". Are you sure of what you say? AFAIK sort(key=lambda x: somefunc..)) will do decorate/sort/undecorate under the hood, behaving like ruby's #sort_by and like your version. OTOH sort(cmp=lambda x,y: something.. ) will behave like ruby's #sort.