How can I use random.sample & random.choice

99封情书 提交于 2021-02-19 11:44:21

问题


I am trying to use random.sample and random.choice to make a simple game. What I want to do is get 8 words randomly from the candidateWords list (this list has 100 words) and then randomly pick 1 word out to be the answer.

Right now the for loop is showing all my words from the candidateWords list and at

one = random.choice(candidateWords)

is not picking the chosen word from the 8 words. I haven't able to generate 8 words in the first place so I know why this isn't working properly.

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)

回答1:


You need to just follow the flow of your program as it executes one statement at a time. First make the sample of 8 words, then choose one of those.

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)


来源:https://stackoverflow.com/questions/36265500/how-can-i-use-random-sample-random-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!