简体   繁体   中英

How to shuffle a list 6 times?

I want to shuffle a list 6 times but I keep getting the same result for all the 6 occasions. Can somebody help me find where the fault is?

Here is the code I used

import random
lis1=[0,1,2,3]
lis2=[]
for i in range(6):
    random.shuffle(lis1)
    lis2.append(lis1)
print lis2

And here is a sample result I got

[[1,3,2,0],[1,3,2,0],[1,3,2,0],[1,3,2,0],[1,3,2,0],[1,3,2,0]]

If I get jumbled lists, how can I sort them in ascending order? As in,I want to get this -

[[0,1,2,3],[2,3,1,0],[2,1,3,0],[1,0,3,2]]

into this-

[[0,1,2,3],[1,0,3,2],[2,1,3,0],[2,3,1,0]]

First, your code repeatedly inserts a lis1 reference into lis2 . Since lis1 stays the same all this time, all of lis2 elements end up pointing to the same object. To fix this, you need to change the append() line to make a copy of the list each time:

lis2.append(lis1[:])

Now, to sort the result simply call sort() after the loop:

lis2.sort()

Try something simpler:

>>> first = [0,1,2,3]
>>> jumbled = [random.sample(first, len(first)) for i in range(6)]
>>> ordered = sorted(jumbled)
>>> jumbled
[[0, 3, 2, 1], [1, 0, 2, 3], [0, 2, 1, 3], [0, 1, 2, 3], [0, 2, 3, 1], [0, 3, 2, 1]]
>>> ordered
[[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 2, 1], [0, 3, 2, 1], [1, 0, 2, 3]]

Store copy of lis1 not actual lis1 do this:

lis2.append(lis1[:])

Then code will be:

import random
lis1=[0,1,2,3]
lis2=[]
for i in range(6):
    random.shuffle(lis1)
    lis2.append(lis1[:])

print lis2

Output:

[[2, 3, 1, 0], [0, 3, 2, 1], [3, 0, 1, 2], [1, 2, 0, 3], [3, 0, 2, 1], [1, 0, 3, 2]]
import random
lis1=[0,1,2,3]
lis2=[]
for i in range(6):
    r = random.randint(0,len(lis1))
    #print(r)
    lis2.append(lis1[r:]+lis1[:r])
print(lis2)
print(sorted(lis2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM