首页 > 解决方案 > 将整数列表转换为与另一个列表中的位置兼容的内容创建刽子手游戏时

问题描述

我最近一直在从事刽子手项目,我使用 enumerate 来获取已猜到的字母的位置,因此我可以将其放入列表中,但是当我尝试将其放入“猜测”列表时,它会出现:编辑:我明白你不能简单地通过 int(list) 将整个列表更改为一系列整数,它只是一个占位符

这是我的代码

import random
lines = []
with open('words.txt', 'r') as f:
for line in f:
    line = line.strip()
    lines.append(line)
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer =         ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
= 1
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
location = [i for i, a in enumerate(choice) if a == guess]
print(location)
if wrong == 6:
    print("Sorry, you have killed yourself.")
    guessed = True
elif not location:
    wrong += 1
    print("Sorry, that was not part of the word!")
    print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
    answer[int(location)] = guess
    print(answer[0:len(choice)])
    print("Congratulations! You have won!")
    guessed = True
else:
    right += 1
    answer[location] = guess
    print(answer[0:len(choice)])

标签: python

解决方案


您的代码除此之外还有其他问题,但作为您手头的问题,它在这里:

elif right == len(choice):
    answer[int(location)] = guess
    print(answer[0:len(choice)])
    print("Congratulations! You have won!")
    guessed = True
else:
    right += 1
    answer[location] = guess
    print(answer[0:len(choice)])

你的两个语句answer[int(location)] = guessanswer[location] = guess如果你打印location它是一个列表,对于一个 4 个字母的单词示例vashlocation是一个范围列表,[0,3]你试图将整个list作为一个范围传递,index无论你是否将其转换为它都int不起作用。

请尝试此修改,这不是一个完整的解决方案,我不想带走你在这个项目上的旅程,但这会让你感动:

import random
lines = ['hey', 'this', 'that']
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer =         ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
right = 0
print(choice)
while not guessed:
    guess = input("Guess a letter!")
    #location = choice.find(guess)
    if wrong == 6:
        print("Sorry, you have killed yourself.")
        guessed = True
    elif guess not in choice:
        wrong += 1
        print("Sorry, that was not part of the word!")
        print("You have", (6 - wrong), "guesses left")
    elif right == len(choice):
        print(answer)
        print("Congratulations! You have won!")
        guessed = True
    else:
        right += 1
        answer[choice.index(guess)] = guess
        print(answer[0:len(choice)])

推荐阅读