从Python数组中删除并恢复到之前状态

1 投票
1 回答
781 浏览
提问于 2025-04-18 05:32

我正在写一个程序,这个程序会向用户展示一个经过编码的单词。用户可以输入一个字符,看看这个字符是否在编码后的单词里。如果用户输入了一个字符,我想让他们有一次机会可以删除他们的输入,并把原来的字符恢复到数组中。

这是我目前的代码 - 我已经开始开发程序的一部分,这部分会把每个输入的字符添加到一个列表里。我的问题是,我该如何把字符恢复到原来的样子。

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: ")

有什么想法吗?

1 个回答

0

这可能用一个 list 来处理会更简单:

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

撰写回答