random.randint 在循环中使用相同的种子

random.randint using the same seed whilst in a loop

我对随机数一直很感兴趣,但是在循环中尝试生成随机数时,如下面的代码

success = 0
times = 0

for i in range(0,10):
    while success == 0:

        numbers = [0,0,0,0,0,0,0,0,0,0]

        for j in range(0,9):

            x = int(random.randint(0,9))
            numbers[x] = 1

            count = numbers.count(1)

        if count == 1:
            success = 1
        else:
            times += 1


    print(times)
    print(numbers)

输出:

17160
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
17160
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
17160
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
17160
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
17160
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]

等等。我想看看它必须尝试的平均时间,但每次都得到相同的结果会毁了它。 有没有办法使用rand函数每次得到不同的随机数?

您的代码会重复执行,直到 10 个随机整数都在 numbers 中设置相同的位置。那设置 success 然后你再试一次。问题是您永远不会清除 success,因此 while success == 0: 不是 True 并且循环不会 运行。解决方法是在外循环中重新设置success

success = 0
times = 0

for i in range(0,10):
    while success == 0:

        numbers = [0,0,0,0,0,0,0,0,0,0]

        for j in range(0,6):

            x = int(random.randint(0,6))
            numbers[x] = 1

            count = numbers.count(1)

        if count == 1:
            success = 1
        else:
            times += 1


    print(times)
    print(numbers)
    success = 0                  # <== the fix