为什么这个 while 循环在 Python 中永不停止

Why does this while loop never stops in Python

我正在尝试使用 Python 3.8 生成包含 100 个唯一随机数的列表。为此,我使用以下代码块:

import random

list_1_unique = [random.randint(0,30)]


for i in range(1, 100):
    x = random.randint(0, 30)
    while x in list_1_unique:
        x = random.randint(0, 30)
    list_1_unique.append(x)
    
list_1_unique

但是一旦我 运行 它 Ipython 控制台永远不会停止,所以它进入了永恒的循环,我不明白为什么?有人能猜出为什么吗?

以下情况导致无限循环:

while x in list_1_unique

如果第一次进入 while 循环时 x 恰好在列表中,那么你就完蛋了。因为这重复了 100 次,你猜怎么着,它一定会发生。

您 运行 for 循环的次数大于您可以从 randint 中获得的可能不同值的数量,因此在 30 次左右之后步骤您的列表 list_1_unique 将具有所有可能的值,并且在 31° 步骤中您将进入无限循环,因为您生成的 x 的任何值都将在您的列表中,因此您无法跳出while循环

换句话说,你不能从一个只有 30 件物品的盒子里挑选 100 件物品。

如果你想要一个 N 个随机数的样本更好地使用 random.sample

>>> import random
>>> random.sample(range(1000),10)
[840, 872, 312, 952, 826, 867, 99, 4, 132, 745]
>>>