Python list does not shuffle in a loop

2020-05-28 19:37发布

问题:

I'm trying to create an randomized list of keys by iterating:

import random

keys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys

This works perfect. However, if I put it in a loop and capture the output:

a = []
for x in range(10):
    random.shuffle(keys)
    a.append(keys)

I am getting 10 times of the same shuffle?! Obviously something is fundamentally wrong here... Thanks in advance.

回答1:

The problem is that you are shuffling the list in place and then adding the reference of the list to the combined list. Thus you end up with same list structure 10 times. "Fundamental change" is that the list has to be copied before appending it.

Here is a bit more "pythonic" way of achieving the same result with list comprehension.

import random

def shuffleACopy(x):
        b = x[:] # make a copy of the keys
        random.shuffle(b) # shuffle the copy
        return b # return the copy

keys = [1,2,3,4,5,6,7,8]
a = [shuffleACopy(keys) for x in range(10)]
print(a)


回答2:

Hypnos has already answered a very correct solution, so I'm just giving you a more visual way to understand what happened and how to spot those kind of things in the future:

import random
keys = ['1', '2', '3', '4', '5']
a = []
for x in range(10):
    random.shuffle(keys)
    a.append(keys)
    print a

gives:

[['4', '5', '3', '2', '1']]
[['2', '5', '1', '4', '3'], ['2', '5', '1', '4', '3']]
[['2', '5', '4', '1', '3'], ['2', '5', '4', '1', '3'], ['2', '5', '4', '1', '3']]
[['5', '4', '3', '1', '2'], ['5', '4', '3', '1', '2'], ['5', '4', '3', '1', '2'], ['5', '4', '3', '1', '2']]
[['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5'], ['1', '4', '3', '2', '5']]
[['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5'], ['2', '3', '4', '1', '5']]
[['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3'], ['2', '1', '4', '5', '3']]
[['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1'], ['2', '5', '3', '4', '1']]
[['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1'], ['3', '5', '2', '4', '1']]
[['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1'], ['4', '2', '3', '5', '1']]

Also, noting that random.shuffle does not return anything, you can start suspecting that the transformation is done in place.