在python中,如何将具有不同索引的重复值插入到空列表中?

在python中,如何将具有不同索引的重复值插入到空列表中?,python,python-3.x,Python,Python 3.x,我正在尝试构建一个基本程序,计算机从预先存在的列表中选择一个单词(称为“单词”),用户必须猜出合适的字母才能猜出这个单词。到目前为止,主要功能是这样的: def game(): word = random.choice(words) while ' ' or '-' in word: word = random.choice(words) if ' ' or '-' not in word: break print(

我正在尝试构建一个基本程序,计算机从预先存在的列表中选择一个单词(称为“单词”),用户必须猜出合适的字母才能猜出这个单词。到目前为止,主要功能是这样的:

def game():
    word = random.choice(words)
    while ' ' or '-' in word:
        word = random.choice(words)
        if ' ' or '-' not in word:
            break
    print(f'Hint: The chosen word is {len(word)} letters long')
    letters = list(word)
    progress = []
    while True:
        guess = str(input('Guess a letter: '))
        if len(guess) > 1:
            print('Sorry, guess a single letter: ')
        if guess in word:
            print(f'The letter {guess} is in the word')
            for i, j in enumerate(letters):
                if progress.count(guess) >= letters.count(guess):
                    break
                elif j == guess:
                    progress.insert(i, j)
            print('Current progress: ' + '-'.join(progress))
            if len(progress) == len(word):
                if letters[:] == progress[:]:
                    print('Congrats! You found the word: ' + str(word))
                    break
        elif guess not in word:
            print(f'The letter {guess} is not in the word: Try Again')
            continue

我的问题是for循环,其中我使用枚举(y)和相应的“elif j==guess”条件。我注意到,在运行该函数时,如果重复的字母是连续的,则代码会工作(例如:在单词“chilly”中,如果我键入“l”,则函数会正确显示两个l,并且游戏会按预期工作)。但是,如果字母分别重复(例如:单词“cologne”),则函数不会在两个o之间插入“l”,并将两个o保持在一起,从而防止猜测正确的单词。有没有其他方法可以解决这个问题?

您应该记住已经猜到的字母,并简单地将打印操作应用于您记住的任何字母,并对单词中的任何其他字母使用
-

您的错误源于您的列表和计数方法,以记住哪些字母要打印或不打印

我修复了不正确的if条件(请参阅了解更多信息)

输出:

Hint: The chosen word is 3 letters long
Guess a letter: The letter e is in the word
Current progress: e-e
Guess a letter: The letter r is not in the word: Try Again
Current progress: e-e
Guess a letter: The letter y is in the word 
Current progress: eye
Congrats! You found the word: eye

OT:
而word中的“”或“-”并不能做你认为它能做的事情。解析表达式时,将其视为编写了
''或('-'在word中)
。但是
是“真实的”;唯一的“false”字符串是空字符串。因此,
表达式始终为真,如果没有条件中断,while循环将永远循环。但是,第5行的条件也有相同的错误,因此
if
总是成功,终止循环。所有这些都无法实现您的目标。OT:如果您希望其他人(例如我们)理解您的代码,请查找比
x
y
更有意义的变量名。代码没有提供任何关于这些变量的用途的提示。@rici很抱歉之前的变量名称含糊不清;将它们编辑为“信件”和“进度”。字母列表的目的是将计算机选择的单词拆分为字母作为单独的索引,进度列表跟踪用户正确识别的字母数量。此外,顶部的初始while循环的目的是删除列表中包含连字符或空格的单词。有没有更有效的方法?
Hint: The chosen word is 3 letters long
Guess a letter: The letter e is in the word
Current progress: e-e
Guess a letter: The letter r is not in the word: Try Again
Current progress: e-e
Guess a letter: The letter y is in the word 
Current progress: eye
Congrats! You found the word: eye