如何在列表中洗牌,同时避免任何项保持在原始位置?

2024-04-27 05:11:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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),但是有没有更简单、更快的方法呢?你知道吗


Tags: 项目代码true列表forismatchrandom
1条回答
网友
1楼 · 发布于 2024-04-27 05:11:49

random.shuffleactual implementation非常简单:

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]

相关问题 更多 >