首页 > 解决方案 > 用 on 循环替换 Python 列表中的特定字符

问题描述

我是编码新手,当我遇到无法解决的大错误时,我尝试制作自己的刽子手游戏。老实说,我对修改列表不太熟悉,所以这可能就是我无法解决这个问题的原因。以下代码是一个函数,它接受一些参数并尝试将修改后的空格返回为不那么空格,例如,如果用户尝试用单词“o”猜测,但单词不是在原始单词的列表中,例如“ love ”,love 的空格类似于_ _ _ _”,所以我尝试这样做,如果字母“o”在原始单词中,我将采用原始单词的位置并将其替换为空白空格以返回类似于“ o _ ”的内容,因为它在原始字符串中:

def revealWord(blankSpaces, letterToReveal, wordPosition, actualString):
countChar = len(actualString)
dividedString = list(actualString)
chara = letterToReveal
joinWord = []

y = 0
while y < countChar:
    y += 1
    if letterToReveal == dividedString[y - 1]:
        print("matched")
        joinWord = dividedString[y - 1]

joinWord = " ".join(blankSpaces)
return joinWord

所以,对我来说,当我尝试猜测这个词时,我会得到这样的结果,你的词有点像这样: 这是输出:

_ _ _ _
try to guess typing a single letter, you have 6 attempts remaining
What is your letter?
 -o
You guessed right! Your letter -o- is #1 time/s in the original word
matched
your word now looks like this: --- _ _ _ _ ---
try to guess typing a single letter, you have 6 attempts remaining
What is your letter?
 -

看?它不会修改任何东西...附加整个代码以获得更好的上下文

import random

wordsdb = ["water", "airplane", "love"]

def keep_playing(currentLives, wordSlctd, blankSpaces):
    print("try to guess typing a single letter, you have {} attempts remaining" .format(currentLives))
    charToGuess = input("What is your letter? \n -")
    check_if_char(blankSpaces, wordSlctd, charToGuess, currentLives)

def hangItUp(hp, wordSlctd, blankSpaces):
    hp -= 1
    print("Your character is not on the string. Hanging him up!")
    print("{} attempts remaining " .format(hp))
    if hp <= 0:
        userResponse = input("Game Over! Waiting for your response...")
        if userResponse == "try again":
            print("restarting the game.")
        else:
            print("Bye bye...")
    else:
        keep_playing(hp, wordSlctd, blankSpaces)
    return hp

def revealWord(blankSpaces, letterToReveal, wordPosition, actualString):
    countChar = len(actualString)
    dividedString = list(actualString)
    chara = letterToReveal
    joinWord = []

    y = 0
    while y < countChar:
        y += 1
        if letterToReveal == dividedString[y - 1]:
            print("matched")
            joinWord = dividedString[y - 1]

    joinWord = " ".join(blankSpaces)
    return joinWord

def check_if_char(blankSpaces, ogWord, selectedChar, currentLives):
    countChar = len(ogWord)
    wordSplitted = list(ogWord)
    wordCount = wordSplitted.count(selectedChar)
    matchedIndexes = []
    revealedWord = ogWord

    if selectedChar in wordSplitted:
        x = 0
        while x < countChar:
            x += 1
            if selectedChar == wordSplitted[x - 1]:
                matchedIndexes.append(x)

        print("You guessed right! Your letter -{}- is #{} time/s in the original word" .format(selectedChar, wordCount))
        revealedWord = revealWord(blankSpaces, selectedChar, matchedIndexes, ogWord)
        print("your word now looks like this: --- {} ---" .format(revealedWord))
        keep_playing(currentLives, revealedWord, blankSpaces)
    else:
        print("your actual word: --- {} ---" .format(revealedWord))
        print("your current word: --- {} ---" .format(blankSpaces))
        currentLives = hangItUp(currentLives, revealedWord, blankSpaces)
        keep_playing(currentLives, revealedWord)



def hangman_game():
    lives = 6
    theSelectedWord = random.choice(wordsdb)
    countTheBlankSpaces = len(theSelectedWord)
    theBlankSpaces = []


    for i in range(countTheBlankSpaces):
        theBlankSpaces.append("_")

    print("your word kinda looks like this: {} " .format(" ".join(theBlankSpaces)))
    keep_playing(lives, theSelectedWord, theBlankSpaces)

hangman_game()

标签: pythonlistloops

解决方案


您可以通过保留猜测字母列表来简化逻辑。因此,您不需要blankSpacesletterToReveal和变量。您还可以使用猜测的字母列表来检查胜利条件。wordPositionactualString

import random

WORDS = ["water", "airplane", "love"]


def revealed_word(word, guessed_letters):
    result = []
    for letter in word:
        if letter in guessed_letters:
            result.append(letter)
        else:
            result.append('-')
    return result


def hangman_game(lives, word):
    guessed_letters = []

    while lives and len(guessed_letters) < len(set(word)):
        print(f"your word kinda looks like this: {revealed_word(word, guessed_letters)}")
        print(f"try to guess typing a single letter, you have {lives} attempts remaining")
        guess = input("What is your letter? ")
        if guess in guessed_letters:
            print("you already guessed this letter, try another one")
        elif len(guess) == 1:
            if guess in word:
                print(f"You guessed right! Your letter -{guess}- is #{word.count(guess)} time/s in the original word")
                guessed_letters.append(guess)
            else:
                lives -= 1
                print("Your character is not on the string. Hanging him up!")
                print("{} attempts remaining ".format(lives))
        else:
            print("please enter one letter only")

    action = input("Game Over! Waiting for your response...")
    if action == "try again":
        print("restarting the game.")
        hangman_game(lives=6, word=random.choice(WORDS))
    else:
        print("Bye bye...")


hangman_game(lives=6, word=random.choice(WORDS))

样本输出:

your word kinda looks like this: ['-', '-', '-', '-', '-', '-', '-', '-']
try to guess typing a single letter, you have 6 attempts remaining
What is your letter? a
You guessed right! Your letter -a- is #2 time/s in the original word
your word kinda looks like this: ['a', '-', '-', '-', '-', 'a', '-', '-']

推荐阅读