我对python很新。 我正在尝试制作解码游戏,玩家可以猜测编码的单词。我已经设法询问用户他们想要替换哪个符号以及他们想用什么字母替换它。但是,下次他们替换符号时,之前的替换不会显示。我知道我需要将用户输入保存到我创建的列表中,但我不确定如何。我想知道是否有人能告诉我我必须做什么。 这是我的代码:
subs2=[] # my list that i want to save the user inputs to
while True:
addpair1=input("Enter a symbol you would like to replace:")
addpair2=input("What letter would you like to replace it with:")
for word in words_list:
tempword = (word)
tempword = tempword.replace('#','A')
tempword = tempword.replace('*', 'M')
tempword = tempword.replace('%', 'N')
tempword=tempword.replace(addpair1,addpair2)
print(tempword)
subs2.append(tempword)
运行此时会发生这种情况:
A+/084&" (the coded words)
A3MANA+
8N203:
Enter a symbol you would like to replace:+
What letter would you like to replace it with:k
Ak/084&"
A3MANAk (the first substitution)
8N203:
Enter a symbol you would like to replace:J
What letter would you like to replace it with:/
A+/084&"
A3MANA+ ( the 2nd one)
8N203:
Enter a symbol you would like to replace:
正如您所看到的,之前的替换不会保存。我在网上看了看,我尝试过的东西都不起作用。如果有人能帮助我,我将非常感激
答案 0 :(得分:2)
在您输入之后,保存在刚刚输入的subs2
列表中:
subs2.append((addpair1, addpair2))
然后在你的循环中,你现在只做
tempword=tempword.replace(addpair1,addpair2)
相反,是一个辅助循环:
for ap1, ap2 in subs2:
tempword=tempword.replace(ap1,ap2)
并在循环结束时丢失更多append
。
这应该可行,但对于许多替换来说效率不高,因为您多次复制tempword
的小变体。如果每个tempword
都是单个字符,那么将dict
转换为可变序列(字符列表)会更快,使用addpair1
进行替换它出现了。
因此,如果该条件确实存在我的代码,而不是......:
subs2 = {'#':'A', '*':'M', '%':'N'}
while True:
while True:
addpair1=input("Enter a symbol you would like to replace:")
if len(addpair1) != 1:
print('Just one character please, not {}'.format(len(addpair1)))
continue
if addpair1 in subs2:
print('Symbol {} already being replaced, pick another'.format(addpair1))
continue
break
addpair2=input("What letter would you like to replace it with:")
subs2[addpair1] = addpair2
for word in words_list:
tempword = list(word)
for i, c in enumerate(tempword):
tempword[i] = subs2.get(c, tempword[i])
tempword = ''.join(tempword)
print(tempword)
在多次替换的情况下,语义与原始代码不同,但在这种情况下,它们可能会正确地为您完成,具体取决于您确切的所需规格。