随机而不重复? [英] Random without repetition?

查看:38
本文介绍了随机而不重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

随机导入标签 = []对于范围内的 i (1, 8):item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"])如果项目不在选项卡中:打印(项目)别的:tab.append(item)继续

解决方案

for 循环中使用 random.shuffle 在这里.

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

<预><代码>>>>随机导入>>>tab = ["house", "word", "computer", "table", "cat", "enter", "space"]>>>random.shuffle(标签)>>>打印标签

<小时>

至于您的原始代码,那是行不通的,因为您编写的 if else 块可确保列表 tab 中没有添加任何元素.您可以通过删除 else 块来纠正这个问题,如下所示:

<预><代码>>>>对于范围内的 i (1, 8):... item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"])...如果项目不在选项卡中:...打印(项目)... tab.append(item)...屋猫空间进入

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

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


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.

这篇关于随机而不重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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