我有一个大的二维列表(列表的列表),每个元素包含一个由整数、字符串和字典组成的列表。我希望能够确定任何被修改的元素的“路径”(例如[2] [3] [2] ["items"] [2]最差!),并在修改时触发此操作。这个列表太大了,无法扫描并查看已更改的内容!理想情况下,我还想要一个新元素的副本,尽管这可以稍后找到。
我的第一次尝试是创建一个类,并覆盖其__setattr__方法:
然而,
因此,总结一下,我希望有一种方法可以告诉我发生了什么更改(索引/键列表),并且需要在发生更改时立即发生,因为扫描整个列表太昂贵了。我也不能依赖修改列表的代码提供详细信息。如果这在第n个嵌套列表中不可能实现,那么我可以使用只给出前两个索引的内容,因为那里的数据不会太大以至于无法扫描。非常感谢您的帮助!编辑:仍然没有成功,尽管这个问题Track changes to lists and dictionaries in python?似乎接近我所需要的。不幸的是,我不太擅长类,并需要会类的人的帮助!编辑:看了这个Python: Right way to extend list让我想到继承
我的第一次尝试是创建一个类,并覆盖其__setattr__方法:
class Notify():
def __setattr__(self, name, value):
self.__dict__[name] = value #Actually assign the value
print name, value #This will tell us when it fires
然而,
__setattr__
方法仅在设置未通过索引(或键)访问的变量时触发,因为这似乎将调用外部的list()/dict()类而不是我们的类。>>> test = Notify()
>>> test.var = 1 #This is detected
var 1
>>> test.var = [1,2,3] #Now let's set it to a list
var [1, 2, 3]
>>> test.var[0] = 12 #But when we assign a value via an index, it doesn't fire
>>> test.var
[12, 2, 3] #However it still assigns the value, so it must be talking to the list itself!
因此,总结一下,我希望有一种方法可以告诉我发生了什么更改(索引/键列表),并且需要在发生更改时立即发生,因为扫描整个列表太昂贵了。我也不能依赖修改列表的代码提供详细信息。如果这在第n个嵌套列表中不可能实现,那么我可以使用只给出前两个索引的内容,因为那里的数据不会太大以至于无法扫描。非常感谢您的帮助!编辑:仍然没有成功,尽管这个问题Track changes to lists and dictionaries in python?似乎接近我所需要的。不幸的是,我不太擅长类,并需要会类的人的帮助!编辑:看了这个Python: Right way to extend list让我想到继承
list
可能是一个坏主意。我使用代理类来编写了以下代码。但是,原始问题仍然存在,即对嵌套列表的修改不记录。类组合而不是继承是一个好主意吗?from UserList import UserList
class NotifyList(UserList):
def __init__(self, initlist=None):
self.data = []
if initlist is not None:
if type(initlist) is list:
self.data[:] = initlist
elif isinstance(initlist, NotifyList):
self.data[:] = initlist.data[:]
else:
self.data = list(initlist)
def __setitem__(self, key, item):
if type(item) is list:
self.data[key] = NotifyList(item)
else:
self.data[key] = item
print key, item
def append(self, item):
if type(item) is list:
self.data.append(NotifyList(item))
else:
self.data.append(item)
print self.index(item), item
__setattr__
中检查值的类型,如果它是一个列表,你可以将它包装在一个 Notify 对象中? - lelloman