简体   繁体   English

处理列表中多次出现的元素

[英]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. ....所以基本上在字符部分,只有第一次出现的猜测字符被实现到 word_to_guess 列表中。 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. index只会返回你的角色第一次出现的索引。

You should use enumerate to iterate on the characters and indices at the same time:您应该使用enumerate同时迭代字符和索引:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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