Python中无重复的随机 [英] Random without repetition in Python
问题描述
我想编写一个程序,以随机顺序显示列表的所有元素,而无需重复. 在我看来,它应该可以工作,但是只能重复打印这些元素.
I want to write a program that displays all the elements of a list in random order without repetition. It seems to me that it should work, but only prints those elements with repetition.
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
推荐答案
Instead of random.choice
within the for
loop, use random.shuffle
here.
这样,可以确保您的列表中包含所有元素,同时还保持了随机顺序的要求:
This way, your list is guaranteed to be have all the elements, while also maintaining the requirement of random order:
>>> import random
>>> tab = ["house", "word", "computer", "table", "cat", "enter", "space"]
>>> random.shuffle(tab)
>>> print tab
对于您的原始代码,这将不起作用,因为您编写的if else
块可确保在列表tab
中未添加任何元素.您可以通过删除else块来更正此问题,如下所示:
As for your original code, that will not work, since the if else
block as you've written ensures that no element is added within the list tab
. You could correct that by removing the else block like below:
>>> 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
但是现在您将需要更改逻辑,以便随机返回相同值的运行不会影响输出的数量.
But now you will need to alter the logic so that the runs in which same value is randomly returned don't affect the number of outputs.
这篇关于Python中无重复的随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!