我正在制作随机建议脚本。我在搜索中遇到了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应该也是这样做的吗?
答案 0 :(得分:2)
是的,只需拨打一次random.sample()
即可:
outList = random.sample(myDict.keys(), myOutput)
您可以从代码中删除以下行:
outList = list()
counter = 1
以及整个while
循环。
答案 1 :(得分:0)
是的,你应该使用random.sample()
。它将使您的代码更清晰,作为奖励,您可以获得性能提升。
循环解决方案的性能问题:
a)在选择任何数字之前必须检查输出列表
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)