Randomize list order

Warren Postma embed at geocities.com
Thu Feb 22 12:22:40 EST 2001


You know, an in-place list.scramble() method would be nice; It could also be
useful card games and self test scripts. ;-)

I even have another use for it....

I have a BSDDB B+Tree file that when created all in one fell swoop, likes to
have its primary keys inserted in Chaotic order.  So, I wonder, is there a
better way to scramble my keys, or is this the most efficient way (lambda
would be less efficient even if on one line, since it would be generating
the necessary functions on demand, more or less, right?).

Warren

----

# scramble a list:

import random

def _scr1(a):
    "turns item a into (random#,a) pairs"
    return (random.randint(0,1000000),a)

def _scr2(a):
    "gets x from (random#,x) pairs"
    return a[1]

def _scramble_list( l ):
    "return a scrambled version of the list l. used by lwdb_btree files when
packing, to insert the new rows in random order."
    n = map(  _scr1, l) # create [ ( random1, keyvalue1), .... ] pairs
    n.sort() # sort by random numbers (scrambles list)
    return map( _scr2, n) # return back just the actual key values






More information about the Python-list mailing list