[英]python recursive function and returning non-mutable dictionary
I'm trying to make function VisitAllObjects accept different files and return a dictionary. 我试图使函数VisitAllObjects接受不同的文件并返回字典。 But what I have currently points to the same name?
但是我目前所指的是同一个名字吗? So once gdata is ran, fdata changes to gdata.
因此,一旦运行了gdata,fdata就会更改为gdata。 How can I make it so fdata and gdata equal their respected data from their gh5 files?
如何使fdata和gdata等于其gh5文件中的受尊敬的数据?
f = h5py.File('testfile.gh5', 'r')
g = h5py.File('testfile2.gh5', 'r')
def VisitAllObjects(Group,Path, FileInfo=None):
if FileInfo is None:
FileInfo = {}
for i in Group.items():
if isinstance(i[1], h5py.Group):
VisitAllObjects(i[1], Path + '/' + i[0])
else:
DatasetName = Path + '/' + i[0]
FileInfo[DatasetName] = (Group[DatasetName].shape, Group[DatasetName].dtype)
return FileInfo
fdata = VisitAllObjects(f,'')
gdata = VisitAllObjects(g,'')
With your help and adding file_info when calling visit_all_objects within itself I was able to get this to work. 在您的帮助下,并在自身内部调用visit_all_objects时添加了file_info,我能够使它正常工作。 If you see any problems with this please let me know, I still need to check it more but using fdata and gdata come back with different data and
fdata is gdata
is False. 如果您发现与此有关的任何问题,请告诉我,我仍然需要进行更多检查,但是使用fdata和gdata会返回不同的数据,而
fdata is gdata
是False。 Thanks. 谢谢。
I got it to work with the following: 我可以将其与以下内容一起使用:
def visit_all_objects(Group,Path, file_info=None):
if file_info is None:
file_info = {}
for i in Group.items():
if isinstance(i[1], h5py.Group):
visit_all_objects(i[1], Path + '/' + i[0], file_info)
else:
DatasetName = Path + '/' + i[0]
file_info[DatasetName] = (Group[DatasetName].shape, Group[DatasetName].dtype)
return file_info
Instead of mutating the dictionary, try making a new one, and mutating that. 与其修改字典,不如尝试制作一个新字典,然后对其进行修改。 You could do that by putting
FileInfo = FileInfo.copy()
near the top of the function, right after you handle the case where FileInfo is None
. 您可以在处理
FileInfo is None
的情况之后,将FileInfo = FileInfo.copy()
放在函数顶部附近,以实现此FileInfo is None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.