简体   繁体   中英

Working with multiple occurrences of elements in a list

I'm still a noob when it comes to coding and I'm trying to create my own hangman game. I ran into some difficulties when it comes to guessing characters of a word which occur more than once in a word.

Here's a snippet of my code:

def random_word():
#word generator
randomized = random.randint(0,(len(content_words)-1))
word_to_guess = content_words[randomized].lower()
splitted = []
word_progress = []
for character in word_to_guess:
    splitted.append(character.lower())
    word_progress.append("?")
counter = 0
while counter <= 5:
    print(word_to_guess)
    print(splitted)
    print(word_progress)
    #Start of the game
    options = str(input("Do you want to guess the word or the characters?: ").lower())
    #word
    if options == "word":
        guess_word = input("Please your guess of the word: ").lower()
        if guess_word == word_to_guess:
            print("Correct! The word was " + word_to_guess + " you only needed " + str(counter) + " tries!")
            break
        elif guess_word != word_to_guess:
            counter += 3
            print("You have entered the wrong word ! You now have " + str(5-counter) + " tries left!")
            continue
            #characters
    elif options == "characters":
        guess_character = input("Please enter the character you would like to enter!: ")
        if guess_character in splitted and len(guess_character) ==  1:
            print("Correct! The character " + guess_character.upper() + " is in the word were looking for!" )
            for char in word_to_guess:
                if char == guess_character:
                    word_progress[word_to_guess.index(char)] = word_to_guess[word_to_guess.index(char)]
            continue

....so basically in the character section only the first occurrence of the guessed character gets implemented into the word_to_guess list. What is the best way to handle this problem?

By the way this is the first question I've ever asked regarding to coding and on this platform, please excuse me if I didn't really formulate my problem in the most efficient way.

index will only return the index of the first occurence of your character.

You should use enumerate to iterate on the characters and indices at the same time:

for index, char in enumerate(word_to_guess):
    if char == guess_character:
        word_progress[index] = guess_character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM