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

时间:2014-05-06 12:08:42

标签: python arrays append restore

我正在编写一个程序,程序向用户显示一个已编码的单词。该程序允许用户输入一个字符以查看该字符是否在编码的单词中。如果角色输入一个角色,我想允许他们一次删除他们的条目并将原始角色恢复回阵列。

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

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 :(得分: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))

请注意"list comprehension",它是以下内容的简写版本:

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