我将如何撤消对列表所做的改组并将其恢复到原始顺序:
[1, 2, 3 , 4]
import random
alist = [1, 2, 3, 4]
random.shuffle(alist) # alist is randomly shuffled
答案 0 :(得分:1)
1cb07348-34a4-4741-b50f-c41e584370f7
Youtuber
https://youtube.com/lol
love youtube
shuffles the input sequence in-place。要恢复原始列表,您需要保留一份副本。
random.shuffle
答案 1 :(得分:1)
我只是从A good way to shuffle and then unshuffle a python list问题的公认答案中得到了这个答案,并做了一些小的改动。它工作完美,请参阅@trincot和@ canton7答案以获取更多信息,他们受过良好的教育。
import random
def getperm(l):
seed = sum(l)
random.seed(seed)
perm = list(range(len(l)))
random.shuffle(perm)
random.seed() # optional, in order to not impact other code based on random
return perm
def shuffle(l): # [1, 2, 3, 4]
perm = getperm(l) # [3, 2, 1, 0]
l[:] = [l[j] for j in perm] # [4, 3, 2, 1]
def unshuffle(l): # [4, 3, 2, 1]
perm = getperm(l) # [3, 2, 1, 0]
res = [None] * len(l) # [None, None, None, None]
for i, j in enumerate(perm):
res[j] = l[i]
l[:] = res # [1, 2, 3, 4]
alist = [1, 2, 3, 4]
print(alist) # [1, 2, 3, 4]
shuffle(alist)
print(alist) # shuffled, [4, 3, 2, 1]
unshuffle(alist)
print(alist) # the original, [1, 2, 3, 4]