我正在编写一个随机建议脚本。我在搜索如何确保生成的列表中没有重复项时遇到了 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/