如何在不重复的情况下将数字输入列表?

-1 python random list

我试图以随机顺序列出数字1-24全部列表,为什么这不起作用?

full_list = []

x = 0
while x < 25 :
    n = randint (1,24) 
    while n in full_list:
        n = randint (1,24)
    full_list.append(n)
    x = x + 1
Run Code Online (Sandbox Code Playgroud)

ant*_*ell 7

random有一个shuffle对这个任务更有意义的功能:

ar = list(range(1,25))
random.shuffle(ar)
ar
> [20, 14, 2, 11, 15, 10, 3, 4, 16, 23, 13, 19, 5, 21, 8, 7, 17, 9, 6, 12, 22, 18, 1, 24]
Run Code Online (Sandbox Code Playgroud)

此外,您的解决方案不起作用,因为while x < 25需要while x < 24.当它x = 24(因为randint(1,24)永远不会生成不在列表中的新数字)时,它处于无限循环中.