python - Python如何知道列表是否已被修改
问题描述
对不起,误导性的标题和新手问题。在以下代码中:
lst = [1, 2, 3]
idlst_init = id(lst)
lst.append(4)
del lst[lst.index(4)]
idlst_final = id(lst)
print(idlst_init == idlst_final)
# True
是否有任何编程方式(除了查看代码)来评估某些操作是使用 list 执行的lst
。使用id()
内置显示它是同一个对象,但是甚至可以知道对象修改的“历史”吗?
解决方案
您可以通过子类化collections.UserList来创建自己的类。一个例子:
import collections
class myList(collections.UserList):
def __init__(self, l=None):
super().__init__(l or [])
self.edits = []
def append(self, el):
super().append(el)
self.edits.append(f"added {el}")
def __delitem__(self, idx):
super().__delitem__(idx)
self.edits.append(f"removed element at index {idx}")
def clear(self):
super().clear()
self.edits.append('cleared')
l = myList([1,2,3])
l.append(1)
del l[0]
l.clear()
print(l.__dict__) # {'data': [], 'edits': ['added 1', 'removed element at index 0', 'cleared']}
推荐阅读
- vue.js - 通过 axios 拦截器后的 Vuejs 错误
- excel - VBA .SendUsingAccount 不适用于每台 PC
- r - 在条形图中改变颜色和组名?
- android - 单击默认 MediaRouteControllerDialog 中的“停止投射”后,Chromecast 继续播放
- php - 使用正则表达式,将分隔的单词转换为引用
- r - 如何用 kableExtra 建立一个汇总月份但不汇总其他列的值的表
- wordpress - 如何在 WordPress 定制器中的徽标上方添加描述?
- reactjs - React 以某种方式调用 setState 来修改我的数据
- reactjs - 在firebase的数组中追加元素
- hive - 在配置单元中加载数据时处理多个分隔符