【问题标题】:How can I use random.sample & random.choice如何使用 random.sample 和 random.choice
【发布时间】:2016-07-15 21:34:18
【问题描述】:

我正在尝试使用random.samplerandom.choice 来制作一个简单的游戏。 我想做的是从candidateWords列表中随机取8个词(这个列表有100个词),然后随机挑出1个词作为答案。

现在for 循环正在显示我在candidateWords 列表中的所有单词

one = random.choice(candidateWords)

没有从 8 个单词中选择所选单词。我一开始无法生成 8 个单词,所以我知道为什么它不能正常工作。

import random
candidateWords = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER', 'BASHER', 'BATHED', 'BATHER', 'BEAMED', 'BEANED', 'BEAVER', 'BECKET', 'BEDDER', 'BEDELL', 'BEDRID', 'BEEPER', 'BEGGAR', 'BEGGED', 'BELIES', 'BELLES', 'BENDED', 'BENDEE', 'BETTER', 'BLAMER', 'BLOWER', 'BOBBER', 'BOLDER', 'BOLTER', 'BOMBER', 'BOOKER', 'BOPPER', 'BORDER', 'BOSKER', 'BOTHER', 'BOWYER', 'BRACER', 'BUDGER', 'BUMPER', 'BUSHER', 'BUSIER', 'CEILER', 'DEADEN', 'DEAFER', 'DEARER', 'DELVER', 'DENSER', 'DEXTER', 'EVADER', 'GELDED', 'GELDER', 'HEARER', 'HEIFER', 'HERDER', 'HIDDEN', 'JESTER', 'JUDDER', 'KIDDED', 'KIDDER', 'LEANER', 'LEAPER', 'LEASER', 'LEVIED', 'LEVIER', 'LEVIES', 'LIDDED', 'MADDER', 'MEANER', 'MENDER', 'MINDER', 'NEATER', 'NEEDED', 'NESTER', 'PENNER', 'PERTER', 'PEWTER', 'PODDED', 'PONDER', 'RADDED', 'REALER', 'REAVER', 'REEDED', 'REIVER', 'RELIER', 'RENDER', 'SEARER', 'SEDGES', 'SEEDED', 'SEISER', 'SETTER', 'SIDDUR', 'TEENER', 'TEMPER', 'TENDER', 'TERMER', 'VENDER', 'WEDDER', 'WEEDED', 'WELDED', 'YONDER']

def wordlist():
    for index, item in enumerate(random.sample(candidateWords, len(candidateWords))):
        print(index, ") ", item, sep='')

one = random.choice(candidateWords)

print("Welcome to the Guess-The-Word Game.\nThe Password is one of these words:")
wordlist()
print(one)

【问题讨论】:

  • 如果你只想要8个,为什么要把len(candidateWords)传递给.sample?为什么你从完整列表中选择one,而不是较短的列表?
  • 您好,感谢您的回复。我发现如果我输入 8 而不是 len() 我可以从列表for index, item in enumerate(random.sample(candidateWords, 8)): 中得到 8 个单词,而选择一个单词是因为这个单词将是 8 个选项中的答案。跨度>

标签: python python-3.x


【解决方案1】:

您只需遵循程序的流程,因为它一次执行一条语句。先做8个词的样本,然后选择其中一个。

import random
candidateWords = [...]

def wordlist(words):
    for index, item in enumerate(words):
        print(index, ") ", item, sep='')

available_words = random.sample(candidateWords, 8)
one = random.choice( available_words )

print("Welcome to the Guess-The-Word Game.\nThe Password is one of these words:")
wordlist(available_words)
print(one)

【讨论】:

  • 嗨 dsh,我想你已经为我中了大奖!这就是我想要做的。因为我是编程新手,所以我仍然无法完全理解流程,但是通过阅读您的代码,我可以理解您所做的事情。非常感谢。
  • 只需按顺序执行每个语句:创建列表、定义函数、调用函数并将结果分配给名称、调用函数并将结果分配给名称、打印消息、调用一个函数,在该函数中迭代打印项目的参数,从函数返回,打印一个对象。除了函数调用,语句是从上到下执行的。注意分配,因为这些会改变名称的含义。
猜你喜欢
  • 2017-04-16
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
相关资源
最近更新 更多