随机播放列表和 return 个副本

Shuffle a list and return a copy

我想打乱一个数组,但我只找到了类似 random.shuffle(x) 的方法,来自 Best way to randomize a list of strings in Python

我可以做类似的事情吗

import random
rectangle = [(0,0),(0,1),(1,1),(1,0)]
# I want something like
# disorderd_rectangle = rectangle.shuffle

现在我只能逃避

disorderd_rectangle = rectangle
random.shuffle(disorderd_rectangle)
print(disorderd_rectangle)
print(rectangle)

但是 returns

[(1, 1), (1, 0), (0, 1), (0, 0)]
[(1, 1), (1, 0), (0, 1), (0, 0)]

所以original array也改变了。我怎样才能创建另一个打乱的 array 而不改变原来的?

使用copy.deepcopy创建数组副本,打乱副本。

c = copy.deepcopy(rectangle)
random.shuffle(c)

这里的人建议使用 deepcopy,这肯定是矫枉过正。您可能不介意列表中的对象相同,您只想打乱它们的顺序。为此,list 直接提供了浅拷贝。

rectangle2 = rectangle.copy()
random.shuffle(rectangle2)

关于您的误解:请阅读http://nedbatchelder.com/text/names.html#no_copies

您需要复制列表,默认情况下 python 仅在您写入时创建指向同一对象的指针:

disorderd_rectangle = rectangle

而是使用这个或者 Veky 提到的复制方法。

disorderd_rectangle = rectangle[:]

它将复制列表。

使用切片做一个浅拷贝,然后打乱拷贝:

>>> rect = [(0,0),(0,1),(1,1),(1,0)]
>>> sh_rect=rect[:]
>>> random.shuffle(sh_rect)
>>> sh_rect
[(0, 1), (1, 0), (1, 1), (0, 0)]
>>> rect
[(0, 0), (0, 1), (1, 1), (1, 0)]

使用random.sample打乱列表而不改变原来的列表。

from random import sample
rect = [(0,0),(0,1),(1,1),(1,0)]
shuffled_rect = sample(rect, len(rect))

上面的代码片段速度较慢,但​​只是另一种方式。