简体   繁体   English

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

[英]Python random.sample same as random.choice with IF Statement

I'm working on a random suggestion script. 我正在研究随机建议脚本。 I came across random.sample in my search for how to make sure I don't have repeats in my generated list. 我在搜索中遇到了random.sample,以了解如何确保生成的列表中没有重复。 Is it the same thing as if I were to use an if statement to test the resultant against the existing list? 是否与使用if语句针对现有列表测试结果是否一样? The number of outputs is set by the user, and the output should be random but not duplicate. 输出数量由用户设置,输出应该是随机的,但不能重复。 Here is my code: 这是我的代码:

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()

I'm not receiving any duplicates in my output list, so is this what random.sample is supposed to do as well? 我在输出列表中没有收到任何重复项,所以random.sample应该也这样做吗?

Yes, a single call to random.sample() will do the trick: 是的,只需对random.sample()进行一次调用即可达到random.sample()

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

You can remove the following lines from your code: 您可以从代码中删除以下几行:

outList = list()
counter = 1

as well as the entire while loop. 以及整个while循环。

Yeah, you should use random.sample() . 是的,您应该使用random.sample() It will make your code cleaner and as a bonus you get a performance increase. 它将使您的代码更整洁,并且作为奖励,您可以提高性能。

Performance issues with your loop solution: 循环解决方案的性能问题:
a) It has to check in the output list before choosing any number a)必须在选择任何数字之前检查输出列表
b) does rejection sampling, so the expected time will be higher as the input number approaches the length of the list. b)进行拒绝采样,因此随着输入数字接近列表的长度,预期时间会更长。

def myRandom():
    myOutput = input("How many suggestions would you like?")
    myDict = {
    "The First":1988,
    "The Second:": 1992,
    "The Third": 1974,
    "The Fourth": 1935}
    outList = random.sample(myDict, myOutput)
    print "These are your suggestions: {0}".format(outList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM