How to encode a range and randomly shuffle a list in Python?

Given a list x = [1,0,0,1,1], I can use it random.shuffle(x)several times to shuffle this list, but if I try to do this in a for loop, the list will not be shuffled.

For instance:

x = [1,0,0,1,1]
k = []
for i in range(10):
     random.shuffle(x)
     k.append(x)
return x

Basically, kcontains the same sequence x unshuffled? Any work around?

+4
source share
3 answers

As mentioned in @jonrsharpe, random.shuffleacts on the list in place. When you add x, you add a link to this particular object. Thus, at the end of the loop kcontains ten pointers to the same object!

, . list() .

import random
x = [1,0,0,1,1]
k = []
for i in range(10):
     random.shuffle(x)
     k.append(list(x))
+2

- . :

[random.sample(x, len(x)) for _ in range(10)]

  • random.sample , .
  • len(x) - . , .
  • .
+1

Try the following:

x = [1,0,0,1,1]
k = []
for i in range(10):
     random.shuffle(x)
     k.append(x.copy())
return x

Replacing xwith x.copy(), you add to the knew list, which looks like xat the moment, not x.

0
source

Source: https://habr.com/ru/post/1694268/


All Articles