如何在不重新排列原始列表的情况下重新排列复制的列表? [英] How to shuffle a copied list without shuffling the original list?
问题描述
我正在使用python,并希望将其后写的复制列表改编为txt文件(请参见下面的代码).
I'm using python and want to shuffle a copied list that I write after that into a txt file (see my code below).
为什么随机播放功能也将原始列表随机化?我只将副本用于函数调用.
Why does the shuffle function randomize the original list, too? I only use the copy for the function call.
有什么想法吗?谢谢!
from random import shuffle
def shuffleList2txt(myList):
shuffle(myList)
f = open('randList.txt','w')
f.write(str(liste))
f.close()
return(myList)
liste = [1,2,3,4,5,6,7,8,9,10]
copy = liste
shuffledList = shuffleList2txt(copy)
liste和shuffledList相同!为什么? liste应该是原始列表,shuffledList应该是随机列表....:)
liste and shuffledList are the same ! Why? liste should be the original one and shuffledList should be the shuffled list.... :)
推荐答案
random.shuffle
正常运行.当然,您可以在改组之前复制列表,但最好使用random.sample
,方法是对整个列表进行抽样...
random.shuffle
works in place. Of course you could make a copy of the list prior to shuffling, but you'd be better off with random.sample
, by taking a sample ... of the whole list:
>>> l = [1,2,3,4]
>>> random.sample(l,len(l))
[3, 1, 2, 4]
>>> l
[1, 2, 3, 4]
因此分配random.sample
的结果将为您提供一个新的,经过改组的列表,而无需更改原始列表.
so assigning the result of random.sample
gives you a new, shuffled list without changing the original list.
这篇关于如何在不重新排列原始列表的情况下重新排列复制的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!