python - 如何跟踪列表中更改的元素
问题描述
对于这个程序,我使用了一个包含 4 个元素的列表。当我改变一个时,我可能想把它放在一个变量中,以了解哪个元素被改变了。例如:
原始列表:['B', 'B', 'B', 'B'] 新列表:['*', 'B', 'B', 'B']
所以有了这个,我怎样才能让我的程序知道元素 0 被改变了?
解决方案
您可以创建一个子类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]
推荐阅读
- node.js - 如何在 ejs 模板中显示嵌套数组值?
- c# - 无法解析符号“HasRequired”实体框架核心
- javascript - 如何在长数字上轻松移动逗号
- python - 替换双引号外的逗号 - Python - 正则表达式
- asdf-vm - 如何将 asdf 与 haskell 一起使用
- system - “at”在分布式系统中是什么意思?
- connection - 如何在 2 台设备(如 torrent)之间建立 p2p 连接
- reactjs - 反应倒数计时器没有很好地减少,它不一致地改变数字
- node.js - 带有 PM2 的节点服务器以 SIGTERM 超时关闭:1600
- python - Python CSV 到数组