生成一个列表的随机置换

2024-09-28 05:25:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个“终端黑客”游戏,但我被困在某个地方。
以下是我的代码当前的外观:

import random

candidateWords = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER'] #etc, etc

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

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

我试着列出一个8个单词的列表,并列举出每个单词的数字。然后,从这8个词中,我需要随机选择一个词作为答案,但我不知道怎么做。在

我想用random.sample()random.choice()。在


Tags: sample代码终端游戏index地方etcrandom
1条回答
网友
1楼 · 发布于 2024-09-28 05:25:22

random.sample()的第二个参数应为<;=第一个参数的长度,否则将生成异常。
剩下的代码似乎没问题。在

import random

candidateWords = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER']

candidateWordsShuffled = random.sample(candidateWords, min(len(candidateWords), 8))


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

one = random.choice(candidateWordsShuffled)
print(one)

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

相关问题 更多 >

    热门问题