当他们在char列表Python中得到正确的字母时通知用户

时间:2015-06-24 15:54:34

标签: python python-3.x

如果用户在列表中输入了正确的字母,我该如何告诉用户?我所知道的唯一方法是插入索引,但这并不是非常灵活,特别是当单词的长度不同时。

import random

possibleWords = [["apple"], ["grapefruit"], ["pear"]]
randomWord = random.choice(possibleWords)
anotherWord = ''.join(randomWord)
finalWord = list(anotherWord)
maxTries = list(range(0, 11))
attemptsMade = 0
triesLeft = 10

print("Hangman!")
print("\nYou got {} tries before he dies!".format(maxTries[10]))
print("There's {} possible letters.".format(len(finalWord)))

for tries in maxTries:
    userChoice = input("> ")

    if userChoice == finalWord[0]:
        print("You got the first letter correct! It is {}.".format(finalWord[0]))

    else:
        print("Ouch! Wrong letter! {} tries remaining.".format(triesLeft))

    attemptsMade += 1
    triesLeft -= 1

3 个答案:

答案 0 :(得分:0)

谈论列表中的字符,或者 - 我认为更有可能出现在你的情况下 - 你可以检查单词中的字符

if userChoice in finalWord:
        # [...] do stuff here

并进一步使用索引函数来确定位置(或多个出现时的位置)。

finalWord.index(userChoice)

您可以确定使用index()函数直接使用返回值。

答案 1 :(得分:0)

使用Python"""用于检查某些内容是否在列表/可迭代内的关键字。

if userChoice in finalWord:

虽然为此,我只是使用正则表达式或列表理解来获取索引,因为你可能想要它们用于游戏。

char_indexes = [i for (i, l) in enumerate(finalWord) if l == userChoice]
if len(char_indexes):

答案 2 :(得分:0)

对单词中的字母使用一个集合,每当玩家猜出一个字母时,检查该字母是否仍在该集合中。如果不是,那是一封错误的信;如果是,则删除该字母,然后继续。如果该集合在某个时刻是空的,那么玩家就会猜到该单词的所有字母。

让你入门的东西:

def hangman (word):
    letters = set(word.lower())
    attempts = 5
    while attempts > 0:
        guess = input('Guess a character ')
        if guess[0].lower() in letters:
            print('That was correct!')
            letters.remove(guess[0])
        else:
            print('That was not correct!')
            attempts -= 1

        if not letters:
            print('You solved the word:', word)
            return

hangman('grapefruit')