首页 > 解决方案 > 如何跟踪列表中更改的元素

问题描述

对于这个程序,我使用了一个包含 4 个元素的列表。当我改变一个时,我可能想把它放在一个变量中,以了解哪个元素被改变了。例如:

原始列表:['B', 'B', 'B', 'B'] 新列表:['*', 'B', 'B', 'B']

所以有了这个,我怎样才能让我的程序知道元素 0 被改变了?

标签: python

解决方案


您可以创建一个子类collections.UserList并覆盖您将用于更改列表的方法。这将允许您将行为插入到这些方法中。如果您确保调用 on 方法super(),正常的列表行为将保持不变。例如,由于我们不知道您所说的“我怎样才能让我的程序知道”是什么意思,所以这只是print()为每个方法添加了一个:

from collections import UserList

class NotificationList(UserList):
    def __setitem__(self, index, value):        
        super().__setitem__(index, value)

        # do what you want here
        print(f"setting new value, {value}, at index {index}")
        
    def __delitem__(self, index):
        super().__delitem__(index)

        # do what you want here
        print(f"deleting item at index {index}")

    def append(self, value):
        super().append(value)

        # do what you want here
        print(f"appending value {value}")

        
n = NotificationList([1, 2, 3])
print(n)
# [1, 2, 3]

del n[1]
# deleting item at index 1
print(n)
# [1, 3]

n.append(2)
#appending value 2
print(n)
# [1, 3, 2]

n[2] = 10
# setting new value, 10, at index 2
print(n)
# [1, 3, 10]

推荐阅读