例如,如果我有一个dicts的dict或数组的dict,但我只希望“深度”复制到两个级别的深度是否有一个简单的方法来做到这一点?
我环顾四周,看看是否有一个我可以使用的图书馆或一个例子,但我找不到任何东西.我是Python的新手,否则我会编写子程序来自己做.有任何想法吗?代码片段将会受到赞赏,因为我理解它的速度会比解释如何理解更快.
谢谢.
附加信息:
有些人问我为什么要这样做,我需要一个副本(不是一个参考,因为我要修改一些值,我不想要原来的修改)来自dict的一些项目,但是dict是巨大的(许多决定词)因此我不想炸毁我的记忆足迹
我的代码很快
好的,我放弃了.这比我想象的要困难,我没时间搞清楚.我最近尝试了一些调试/测试代码.
# Deep copy any iteratable item to a max depth and defaults to removing the
# rest. If you want to keep the stuff past max depth as references to orig
# pass the argument else_ref=1. Ex:
# dict_copy = copy_to_depth( dict_orig,2,else_ref=1 )
def copy_to_depth( orig,depth,**kwargs):
copy = type(orig)()
for key in orig:
# Cannot find a reliable and consistent way to determine if the item
# is iterable.
#print orig[key].__class__
#if hasattr(orig[key],'__iter__'):
#if hasattr(orig[key],'__contains__'):
#if iterable( orig[key] ):
#try:
if hasattr(orig[key],'__contains__'):
if depth > 0:
copy[key] = copy_to_depth(orig[key],depth - 1,**kwargs)
else:
if 'else_ref' in kwargs:
copy[key] = orig[key]
else:
copy[key] = 'PAST_MAX_DPETH_ITERABLE_REMOVED'
#except:
else:
copy[key] = orig[key]
return copy
def iterable(a):
try:
(x for x in a)
return True
except TypeError:
return False
people = {'rebecca': 34,'dave': 'NA','john': 18,'arr': [9,8,{'a':1,'b':[1,2]}],'lvl1':
{'arr': [9,'rebecca': 34,'lvl2':
{'arr': [9,'lvl3':
{'rebecca': 34,2]}]}}}}
print people
ppl_cpy = copy_to_depth(people,1)
ppl_cpy['arr'][1] = 'nine' # does not mod orig
ppl_cpy['john'] = 0 # does not mod orig
ppl_cpy['lvl1']['john'] = 1 # does not mod orig b/c copy_to_depth
ppl_cpy['arr'][3]['a'] = 'aie' # does not mod orig
#ppl_cpy['lvl1']['lvl2']['john'] = 2 # Rest cause an error
#ppl_cpy['lvl1']['lvl2']['lvl3']['john'] = 3
print people
print ppl_cpy
ppl_cpy = copy_to_depth(people,1,else_ref=1)
ppl_cpy['john'] = 0 # does not mod orig
ppl_cpy['lvl1']['john'] = 1 # does not mod orig b/c copy_to_depth was 1
ppl_cpy['lvl1']['lvl2']['john'] = 2 # Rest Do not cause error but modifies orig
ppl_cpy['lvl1']['lvl2']['lvl3']['john'] = 3
print people
print ppl_cpy
我无法找到一种可靠且一致的方法来确定该项目是否可迭代.我一直在阅读this post并尝试解决它,但没有一个解决方案似乎适用于我的测试用例.
我将深度复制整个dict并尝试稍后(或不)优化解决方案.
谢谢…
最佳答案
原文链接:https://www.f2er.com/python/439269.html