Scramble Python List
Copy the array then scramble it:
import random
array = range(10)
newarr = array[:] # shallow copy should be fine for this
random.shuffle(newarr)
#return newarr if needs be.
zip(array, newarr) # just to show they're different
Out[163]:
[(0, 4),
(1, 8),
(2, 2),
(3, 5),
(4, 1),
(5, 6),
(6, 0),
(7, 3),
(8, 7),
(9, 9)]
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]
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]