我有一个问题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),但是有没有更简单、更快的方法来做到这一点?
The 实际执行 of 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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)