从python数组中删除并恢复到以前的状态

从python数组中删除并恢复到以前的状态,python,arrays,append,restore,Python,Arrays,Append,Restore,我正在编写一个程序,程序向用户显示一个经过编码的单词。该程序允许用户输入一个字符,以查看该字符是否在编码字中。如果角色输入了一个字符,我希望允许他们一次删除他们的输入并将原始字符恢复回数组 这是我到目前为止的代码——我已经开始开发程序的一部分,它将把输入的每个字符附加到一个列表中。我的问题是我怎样才能恢复到原来的角色 while Encoded_Team != Team: print("\nThe encoded team is", Encoded_Team,"\n") Choo

我正在编写一个程序,程序向用户显示一个经过编码的单词。该程序允许用户输入一个字符,以查看该字符是否在编码字中。如果角色输入了一个字符,我希望允许他们一次删除他们的输入并将原始字符恢复回数组

这是我到目前为止的代码——我已经开始开发程序的一部分,它将把输入的每个字符附加到一个列表中。我的问题是我怎样才能恢复到原来的角色

while Encoded_Team != Team:
    print("\nThe encoded team is", Encoded_Team,"\n")
    Choose = input("Choose a letter in in the encoded team that you would replace: ")
    Replace = input("What letter would you like to replace it with? ")
    array.append(Choose)
    array.append(Replace)
    Encoded_Team = Encoded_Team.replace(Choose, Replace)
    Delete = input("\nWould you like to delete a character - yes or no: ")

有什么想法吗?

使用
列表可能更容易处理:

encoded = list(Encoded_Team)
plaintext = list(Team)
changes = []
while encoded != plaintext:
    print("\nThe encoded team is {0}\n".format("".join(encoded)))
    old = input("Which letter would you like to replace? ")
    indices = [i for i, c in enumerate(encoded) if c == old]
    new = input("What letter would you like to replace it with? ")
    for i in indices:
        encoded[i] = new
    changes.append((old, new, indices))
请注意,这是以下内容的简写版本:

indices = []
for i, c in enumerate(encoded):
    if c == old:
        indices.append(i)
现在,您可以轻松地反转操作,即使
choose
已在
encoded
中:

for old, new, indices in changes:
    print("Replaced '{0}' with '{1}'".format(old, new))
    undo = "Would you like to undo that change (y/n)? ".lower()
    if undo == "y":
        for i in indices:
            encoded[i] = old

Encoded\u Team=Encoded\u Team.replace(replace,Choose)
?或者他们可能正在更改为
编码团队中已经存在的字符。谢谢你的时间和代码-我也许可以在我的程序中使用它。我的问题是,在输入的字符替换了已替换的字符后,我需要能够恢复以前输入的字符,而不是撤消最后输入的字符。我是否需要将所有输入的字符追加到列表中,然后将它们恢复到编码数组中?在我将字符添加到列表后,我有点不确定如何编写程序…@user3608028不要试图在注释中发布代码;这很难读!如果您想保留记录,可以存储一个包含适当数据的列表,例如
changes=[(old1,new1,[i1,i2,i3]),(old2,new2,[i3,i4]),…]
感谢Jon花时间编辑该列表。我要试试这个!嗨,乔恩。这段代码非常好用(谢谢!),我可以把它作为程序的一部分使用!我唯一的问题是,我想让用户选择删除以前的条目,即使他们之前做了一些选择——就像他们有一个选项来纠正以前的错误一样,当他们意识到编码的单词不是他们期望的那样时,一些人会回到游戏中。我不太理解的是在“索引=”之后