Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scramble Python List

Before I ask my question, let me get this straight...

This is not a duplicate of Does anyone know a way to scramble the elements in a list? and Shuffle an array with python, randomize array item order with python. I'll explain why...

I want to know how to scramble an array, and make a new copy. Because random.shuffle() modifies the list in place (and returns None), I want to know if there is another way to do this so I can do scrambled=scramblearray(). If there isn't a built-in function, I could define a function to do this if possible.

like image 888
CoffeeRain Avatar asked Mar 19 '12 13:03

CoffeeRain


2 Answers

Use sorted(). It returns a new list and if you use a random number as key, it will be scrambled.

import random
a = range(10)
b = sorted(a, key = lambda x: random.random() )
print a, b

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [5, 9, 0, 8, 7, 2, 6, 4, 1, 3]
like image 176
koffein Avatar answered Sep 29 '22 15:09

koffein


def scrambled(orig):
    dest = orig[:]
    random.shuffle(dest)
    return dest

and usage:

import random
a = range(10)
b = scrambled(a)
print a, b

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [6, 0, 2, 3, 1, 7, 8, 5, 4, 9]
like image 43
eumiro Avatar answered Sep 29 '22 15:09

eumiro