随机播放列表并返回副本 [英] Shuffle a list and return a copy
问题描述
I want to shuffle an array, but all I find was method like random.shuffle(x)
, from 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)
但是它返回
[(1, 1), (1, 0), (0, 1), (0, 0)]
[(1, 1), (1, 0), (0, 1), (0, 0)]
因此,original array
也已更改.我如何只创建另一个改组的array
,而不更改原始的array
?
So the original array
is also changed. How can I just create another shuffled array
without changing the original one?
推荐答案
这里的人们建议使用深度复制,这肯定是一个过大的杀伤力.您可能不介意列表中的对象相同,而只是想改变它们的顺序.为此,列表直接提供浅表复制.
People here are advising deepcopy, which is surely an overkill. You probably don't mind the objects in your list being same, you just want to shuffle their order. For that, list provides shallow copying directly.
rectangle2 = rectangle.copy()
random.shuffle(rectangle2)
关于您的误解:请阅读 http://nedbatchelder.com/text/names.html#no_copies
About your misconception: please read http://nedbatchelder.com/text/names.html#no_copies
这篇关于随机播放列表并返回副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!