我对 random.shuffle
有疑问。基本上,它可以很好地伪随机化列表中的项目,但在我的例子中,我还想防止项目保留在同一位置。
我想出这段代码是为了确保每个项目都有一个新的位置。
match = True
while match is True:
for i in range(len(initial_list)):
if initial_list[i]==result_list[i]:
random.shuffle(result_list)
match = True
else:
match = False
这段代码通过了测试(如果 shuffle 可以完成的话),但是有没有更简单快捷的方法呢?
最佳答案
actual implementation random.shuffle
非常简单:
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]
稍作修改,我们可以添加您的新要求:
from random import random
def my_shuffle(x):
if len(x) == 1:
raise Exception
for i in reversed(range(1, len(x))):
# pick an element in x[:i] with which to exchange x[i]
j = int(random() * i)
x[i], x[j] = x[j], x[i]
关于python - 如何洗牌列表中的项目,同时避免任何项目留在原来的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41254081/