Python中无重复的随机 [英] Random without repetition in Python

查看:60
本文介绍了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

推荐答案

而不是在for循环中使用random.choice,请使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆