python - 将整数列表转换为与另一个列表中的位置兼容的内容创建刽子手游戏时
问题描述
我最近一直在从事刽子手项目,我使用 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)])
解决方案
您的代码除此之外还有其他问题,但作为您手头的问题,它在这里:
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)] = guess
,answer[location] = guess
如果你打印location
它是一个列表,对于一个 4 个字母的单词示例vash
,location
是一个范围列表,[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)])
推荐阅读
- python - Mac上的Pyinstaller:如何在不先打开终端的情况下打开应用程序?
- javascript - Material UI Swipable Drawer 覆盖 html 样式溢出为隐藏
- javascript - 是否可以在 Javascript 中定义二维集
- android - Xamarin 表单、Plugin.InAppBilling、Android:成功购买后出错
- python - 使用 python 3.8 将 Django 部署到 heroku
- python - Python:无论我尝试什么,我都无法发送电子邮件
- python - Numpy:TypeError:'float'对象不能解释为整数
- node.js - 节点应用程序在部署时如何运行?
- apache-kafka - 如何在生产中运行 MirrorMaker 2.0?
- php - 在商店图片下方添加 Woocommerce 类别