I would like to make a matrix whose lines are different permutations of the following vector=
[1,2,3,4,5,10,10,10,10,10]
I tried to use the random.shuffle function, but it seems that everytime I use that, It redefines all objects to which it is assigned. For example, I have tried the following:
vec=[1,2,3,4,5]
for i in range(5):
vec.append(10)
Matpreferences=[]
for i in range(10):
random.shuffle(vec)
Matpreferences.append(vec)
But then I get a matrix with all lines equal.
eg:
[0, 0, 1.0, 0, 2.0, 3.0, 0, 0.5, 2.5, 1.5, 0]
[0, 0, 1.0, 0, 2.0, 3.0, 0, 0.5, 2.5, 1.5, 0]
[0, 0, 1.0, 0, 2.0, 3.0, 0, 0.5, 2.5, 1.5, 0]
[0, 0, 1.0, 0, 2.0, 3.0, 0, 0.5, 2.5, 1.5, 0]
...
I even tried something like
Matpreferences=[]
for i in range(10):
random.shuffle(vec)
a=vec
Matpreferences.append(a)
But it yields the same results. Is there any simple way to get around that?
Thanks a lot for any help given =)
Answers
You need to make a copy of vec
before you shuffle it:
import random
vec=[1,2,3,4,5]
for i in range(5):
vec.append(10)
Matpreferences=[]
for i in range(10):
v = vec[:]
random.shuffle(v)
Matpreferences.append(v)
Explanation
From your code:
a=vec
Matpreferences.append(a)
Here, a
points at the same data that vec
points at. Consequently, when a
is shuffled, so is vec
and so is everything that points at vec
.
By contrast, because of the subscripting [:]
, this code creates a new and independent copy of the data:
v = vec[:]
Because v
is a separate and independent copy, shuffling v
has no effect on vec
.
Answers
Your adding an object reference to the list. Think of it as a pointer. Each vec that you add to Matpreferences points to the same instance.
Look at this example:
>>> vec = [1,2,3,4,5]
>>> vec2 = vec
>>> random.shuffle(vec)
>>> print vec
[2, 4, 3, 1, 5]
>>> print vec2
[2, 4, 3, 1, 5]
>>>
As you see, the content of vec
and vec2
is the same even though I did not shuffle vec2
.
what you need to do is to copy the content of vec
into a new list and then add that list to Matpreferences
Replace your last line with
Matpreferences.append([x for x in vec])
or
Matpreferences.append(vec[:])
Answers
random.shuffle
shuffles a list in place, so after each call, contents of vec
gets shuffled. Note that vec
is a reference to a list, so when you append vec
10 times in a list, it contains the same reference 10 times. All of them holds the same list. That's why you see the same list. vec
is indeed shuffled 10 times, but you only see the last permutation when you print it.
To fix this, you'll need to make a new copy of vec each time, shuffle the copy and append that to Matpreferences
. Or you can shuffle vec
, then append a copy of it to Matpreferences
.
Copying a list would be easy, the shortest one is, I think, using slicing:
Matpreferences.append(vec[:])