【问题标题】:Deleting from a python array and restoring to previous state从 python 数组中删除并恢复到以前的状态
【发布时间】:2014-05-06 12:08:42
【问题描述】:

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

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

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_Team = Encoded_Team.replace(Replace, Choose)?或者他们可能会变成一个已经在Encoded_Team 中的角色?

标签: python arrays append restore


【解决方案1】:

使用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

【讨论】:

  • 嗨乔恩。感谢您的时间和代码 - 我也许可以在我的程序中使用它。我的问题是,我需要能够在输入的字符替换已经替换的字符后恢复先前输入的字符,而不是撤消输入的最后一个字符。我是否需要将所有输入的字符附加到列表中,然后将它们恢复到编码数组?在将字符附加到列表后,我有点不确定如何对程序进行编码......
  • @user3608028 不要尝试在 cmets 中发布代码;很难读!如果要保留记录,可以存储包含适当数据的列表,例如changes = [(old1, new1, [i1, i2, i3]), (old2, new2, [i3, i4]), ...]
  • 感谢 Jon 抽出宝贵时间进行编辑。我会试试看!
  • 嗨乔恩。该代码完美运行(谢谢!),我可以将其用作程序的一部分!我唯一的问题是,我想让用户选择删除以前的条目,即使他们之前做出了一些选择——就像他们可以选择纠正以前的错误一样,一旦他们意识到这一点,他们就会回到游戏中编码的单词不是他们所期望的。
  • 我不太理解的行是“indices =”之后的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2021-05-22
  • 2019-03-29
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
相关资源
最近更新 更多