如何将用户输入保存到列表python中

2024-06-26 14:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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)

运行此命令时会发生以下情况:

^{pr2}$

如您所见,上一次替换不会保存。我在网上查过,但是我试过的都不管用。如果有人能帮助我,我将不胜感激


Tags: to用户you列表input符号replacelist
1条回答
网友
1楼 · 发布于 2024-06-26 14:31:43

在输入之后,将刚刚输入的对保存在subs2列表中:

subs2.append((addpair1, addpair2))

然后在你的循环中,你现在做的只是

^{pr2}$

相反,执行二次循环:

for ap1, ap2 in subs2:
    tempword=tempword.replace(ap1,ap2)

并在循环结束时丢失进一步的append。在

这应该可以工作,但对于许多替换来说效率不高,因为您要多次复制tempword的小变体。将tempword转换为可变的序列(字符列表)将更快,如果每个addpair1是一个单独的字符,则使用dict作为替换。在

所以如果这个条件成立,我会改为…:

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)

在多个替换的情况下,语义与您的原始代码不同,但是在这种情况下,它们可能会正确地为您工作,具体取决于您所希望的规范。在

相关问题 更多 >