How to shuffle a copied list without shuffling the original list?

故事扮演 提交于 2019-12-20 03:11:40

问题


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.

Any ideas? Thank you !

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 and shuffledList are the same ! Why? liste should be the original one and shuffledList should be the shuffled list.... :)


回答1:


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]

so assigning the result of random.sample gives you a new, shuffled list without changing the original list.



来源:https://stackoverflow.com/questions/47750757/how-to-shuffle-a-copied-list-without-shuffling-the-original-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!