Python random.sample 与带有 IF 语句的 random.choice 相同

标签 python random

我正在编写一个随机建议脚本。我在搜索如何确保生成的列表中没有重复项时遇到了 random.sample。这与我使用 if 语句根据现有列表测试结果是一样的吗?输出的数量由用户设置,输出应该是随机的但不能重复。这是我的代码:

import random
def myRandom():
    myOutput = input("How many suggestions would you like?")
    outList = list()
    counter = 1
    myDict = {
    "The First":1988,
    "The Second:": 1992,
    "The Third": 1974,
    "The Fourth": 1935,
    "The Fifth":2012,
    "The Six":2001,
    "The Seventh": 1994,
    "The Eighth":2004,
    "The Ninth": 2010,
    "The Tenth": 2003}
    while counter <= myOutput:
        thePick = random.choice(myDict.keys())
        if thePick in outList:
            pass
        else:
            outList.append(thePick)
            counter = counter + 1
    print "These are your suggestions: {0}".format(outList)
myRandom()

我的输出列表中没有收到任何重复项,那么这也是 random.sample 应该做的事情吗?

最佳答案

是的,只需调用 random.sample() 即可解决问题:

outList = random.sample(myDict.keys(), myOutput)

您可以从代码中删除以下行:

outList = list()
counter = 1

以及整个 while 循环。

关于Python random.sample 与带有 IF 语句的 random.choice 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628777/

相关文章:

python - 遗传算法中的矢量化育种方法

python - 读取 csv 文件并对特定行执行公式

python - 线性同余发生器 - 弱测试结果

swift - 根据用户数 "likes"根据分布随机找一个用户

python - 如何使用 Python 字符串加载 PhantomJS

python - 如何根据经验确定级别?

python - 更新mongo中的字段类型

c# - NSubstitute 模拟扩展方法

mysql - MySQL 能否生成可以为负数或正数的随机数?

c++ - `std::random_device` 和 `std::mt19937_64` 和有什么区别?