Skip to main content
 首页 » 编程设计

python之随机不重复

2025年05月04日9thcjp

我想编写一个程序,以随机顺序不重复地显示列表的所有元素。 在我看来它应该可以工作,但只会重复打印那些元素。

import random 
 
tab = [] 
 
for i in range(1, 8): 
    item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"]) 
    if item not in tab: 
        print(item) 
    else: 
        tab.append(item) 
        continue 

请您参考如下方法:

在 for 循环中不要使用 random.choice,而是使用 random.shuffle在这里。

这样,您的列表可以保证包含所有元素,同时还保持随机顺序的要求:

>>> import random 
>>> tab = ["house", "word", "computer", "table", "cat", "enter", "space"] 
>>> random.shuffle(tab) 
>>> print tab 

至于您的原始代码,那是行不通的,因为您编写的 if else block 确保不会在列表 tab 中添加任何元素。您可以通过像下面这样删除 else block 来更正它:

>>> for i in range(1, 8): 
...     item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"]) 
...     if item not in tab: 
...         print(item) 
...         tab.append(item) 
...  
house 
cat 
space 
enter 

但是现在您需要更改逻辑,以便随机返回相同值的运行不会影响输出的数量。