如何在 Python 中实现 List-Class 的 undo()-方法

How to implement an undo()-Method for a List-Class in Python

我对 python 有点陌生,我接到了一个任务,要创建一个带有 undo() 方法的 class "UndoList"(类型列表)。此方法应撤消典型的列表操作,如追加、插入、删除...

>>> ul = UndoList([1,2,3])
>>> ul.append(4), print(ul), undo(ul), print(ul)
[1,2,3,4]
[1,2,3]
>>> ul.remove(3), print(ul), undo(ul), print(ul)
[1,2]
[1,2,3]
...

这个 undo() 方法应该只能撤销一个操作(如您在示例中所见)。我的老师给了我提示,在每次操作之前将列表的值保存在实例中。

这是我的 class:

class UndoList(list):

   def __init__(self, lis):
       list.__init__(self, lis)
       self.lis = []

   def __append__(self, lis):
       list.__add__(self, lis)
       return lis

   def undo(self):
       return self

a1 = UndoList([1,2,3])
print(a1), a1.append(4), print(a1)   #[1,2,3] [1,2,3,4]
a1.undo(), print(a1)                 #[1,2,3,4]

所以现在我的问题是:如何在我的 class 中创建一个实例来保存我的实际列表,然后再进行任何操作?是否可以在我的撤销方法中重新运行这个实例?

谢谢!

很简单。但是乏味:您向列表对象添加一个 history 属性。这是一堆以前的变量状态。每个更改操作都需要在更改之前将其当前状态推送到对象的 history 上。 undo 操作只是弹出最近的一个。

您已经注意到您必须重新定义所有更改操作(例如 class 中的 __append__)。

这里有一些代码可以帮助您入门。不过,实际上,最好避免子 classing Python 的标准类型,因为要正确执行此操作,您通常需要重写 every 方法,这可以是相当繁琐且容易出错。

注意 append 方法被称为 append,而不是 __append__。 :) 并且就地改变列表的方法 return None,而不是列表。

from copy import deepcopy

class UndoList(list):
    def __init__(self, *args):
        super().__init__(*args)
        self.old = []

    def append(self, item):
        self.old = deepcopy(self[:])
        super().append(item)

    def extend(self, items):
        self.old = deepcopy(self[:])
        super().extend(items)

    def undo(self):
        temp = deepcopy(self[:])
        self[:] = self.old
        self.old = temp


a = UndoList([1, 2, 3])
print(a)

a.append(4)
print(a)
a.undo()
print(a)
a.undo()
print(a)

a.extend([5, 6])
print(a)
a.undo()
print(a)

输出

[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]

我们使用 def __init__(self, *args) 以便我们可以在不带参数的情况下调用 UndoList() 来获得一个空的 UndoList。

正如评论中提到的 9000,您可能不需要 deepcopy 此处。它通过递归复制每个列表项(不可变项除外)来消耗额外的 RAM,而且速度很慢。使用 deepcopy 确实使 UndoList 健壮。 OTOH,这也意味着从 .old 恢复的项目是原始项目的副本,在某些情况下这是不可取的 - 如果其他对象引用这些项目,则备份过程会中断该连接。

如果您想对此进行试验,只需将备份列表的代码更改为

self.old = self[:]

并且 undo 方法变为

def undo(self):
    self[:], self.old = self.old, self[:]

明智的做法是使用 Abstract Base Classes 构建一个新的 class 而不是子 classing list.

让我们通过例子来理解它: 最初给定一个空数组,我们必须实现四个函数。

我们有以下类型的查询:

  1. Add(value) : 将值添加到数组。

  2. Remove(value) : 从数组中删除值。

  3. 撤消:撤消对数组执行的最后一个操作。

  4. 重做:恢复最近对阵列执行的 UNDO 操作。

例子: 输入:列表=[] 输出:add(1) print(List) List=[1]

          add(2)  print(List)  List=[1,2]
          add(3)  print(List) List=[1,2,3] 
          add(4)  print(List)  List=[1,2,3,4]
          undo()  print(List) List=[1,2,3]
          undo()  print(List)  List=[1,2]
          redo()   print(List)  List=[1,2,3]
          redo()  print(List) List=[1,2,3,4]
          remove(3) print(List)  List=[1,2,4]
          remove(1)  print(List) List=[2,4]
          remove(2)  print(List)  List=[4]
          undo() print(List)  List=[2,4]
          undo() print(List)  List=[1,2,4]
          undo() print(List)  List=[1,2,3,4]
          redo()  print(List)  List=[1,2,4]

方法:这个问题可以通过使用2个列表来解决,首先,我们将制作一个撤消列表,它将跟踪上次执行的操作,它将是一个元组列表,格式为( operation, index, value) 这里如果 operation='a' 意味着执行的最后一个动作是将元素添加到列表中,如果 operation='r' 意味着最后执行的动作是从列表中删除元素。

第二个列表将是重做列表,它将跟踪执行的撤消操作,以便它可以恢复最近的撤消操作。

# Python Program to implement the above approach.

# this is the main list which will be printed after doing any of the above operations
main_list = []

# this is the list for tracking the operations being performed
undo_list = []

# this is the redo list which will keep track of the undo operations done.
redo_list = []                                                             \


def add(value):
    """
    this is the function to add the value to the list
    """
    # index at will we will add the value
    idx=len(main_list)
    # value will be added to the main_list
    main_list.append(value)
    # we will update undo_list, by appending the operation as 'r', as we are adding value to the list, so its undo operation will do the reverse of it, so we will append operation as 'r'.
    undo_list.append(('r',idx,value))
    print(main_list)




def remove(value):
    """
    this is the function to remove the value from the list
    """
    # length of the main_list
    length=len(main_list)
    # if the length of the main_list is 0
    if(length==0):
        return
    # if the value is not present in the main_list
    if value not in main_list:
        return
    # index of the value that we have to remove
    idx = main_list.index(value)
    # removing value from the main_list
    main_list.remove(value)
    # we will update undo_list, by appending the operation as 'a', as we are removing value from the list , so its undo operation will do the reverse of it , so we will append operation as 'a'.
    undo_list.append(('a', idx, value))
    print(main_list)




def undo():
    """
    this is the function to undo the value

    """
     #length of the undo_list
    length = len(undo_list)
     # if  the length of the undo_list is 0 ,means there is nothing to do undo operation
    if(length==0):
        return
    # selecting the latest undo operation that we have to perform
    cur_tuple=undo_list.pop();
    # selecting the type of the operation that we have to perform
    cur_tuple_operation=cur_tuple[0]
    # selecting the index at which we will perform latest undo operation.
    cur_tuple_index=cur_tuple[1]
     # selecting the value on which we will perform the latest undo operation
    cur_tuple_value=cur_tuple[2]
     # if the operation we have to do undo is 'a'
    if(cur_tuple_operation=='a'):
        # adding value to main_list
        main_list.insert(cur_tuple_index,cur_tuple_value)
        # also we will update redo_list by appending the operaion as 'r' as  the undo current operation is 'a' , so redo operation will restore the most recent undo operation beging performed.
        redo_list.append(('r',cur_tuple_index,cur_tuple_value))
    # if the operation we have to do undo is 'r'
    elif(cur_tuple_operation=='r') :
        # removing the value from the main_list
        main_list.pop(cur_tuple_index)
        # also we will update redo_list,by appending the operation as 'a', as the undo current operation is 'r' , so redo operation will restore the most recent undo operation beging performed.
        redo_list.append(('a',cur_tuple_index,cur_tuple_value))
    print(main_list)




def redo():
    """
    this is the function to redo the value
    """
    #length of the redo_list
    length=len(redo_list)
    # if the length of the redo list is 0
    if(length==0):
        return
    # selecting the latest redo operation that we have to perform.
    cur_tuple=redo_list.pop();
    # selecting the type of the operation that we have to perform
    cur_tuple_operation=cur_tuple[0]
    # selecting the index at which we will perform latest redo operation.
    cur_tuple_index=cur_tuple[1]
    # selecting the value on which we will perform the latest redo operation.
    cur_tuple_value=cur_tuple[2]
    # if the operation we have to do redo is 'a'
    if(cur_tuple_operation=='a'):
         # adding value to main_list
        main_list.insert(cur_tuple_index,cur_tuple_value)
    # if the operation we have to do redo is 'r'
    elif(cur_tuple_operation=='r'):
         # removing the value from the main_list
        main_list.pop(cur_tuple_index)
    print(main_list)




add(1)
add(2)
add(3)
remove(2)
add(4)
add(5)
undo()
undo()
undo()
undo()
undo()
undo()
redo()
redo()
redo()
redo()
redo()
redo()