您可能会发现这种改组的实现适合您的需要。在使用它们之前,请确保注意这两个功能之间的区别。
>>> import random
>>> def shuffle(array):
copy = list(array)
shuffle_in_place(copy)
return copy
>>> def shuffle_in_place(array):
array_len = len(array)
assert array_len > 2, 'Array is too short to shuffle!'
for index in range(array_len):
swap = random.randrange(array_len - 1)
swap += swap >= index
array[index], array[swap] = array[swap], array[index]
>>> array = list(range(10))
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle(array)
[7, 2, 3, 5, 8, 6, 0, 1, 9, 4]
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle_in_place(array)
>>> array
[8, 3, 1, 6, 9, 7, 0, 4, 2, 5]
>>>