gpt4 book ai didi

python - 在 python 中,我如何将 dict 深度复制到特定深度?

转载 作者:太空狗 更新时间:2023-10-30 01:16:54 25 4
gpt4 key购买 nike

例如,如果我有一个字典字典或数组字典,但我只想“深”复制到两个级别的深度,是否有一种简单的方法可以做到这一点?

我四处寻找是否有我可以使用的库或示例,但我找不到任何东西。我是 Python 的新手,否则我会自己编写子例程来执行此操作。有任何想法吗?代码片段将不胜感激,因为它比仅仅解释如何操作更能让我理解。

谢谢。

附加信息:

有些人问我为什么要这样做,我需要一份字典中某些项目的副本(不是 ref,因为我要修改某些值,我不想修改原始值)但是字典很大(很多字典的字典)所以我不想炸毁我的内存足迹

到目前为止我的代码

好吧,我放弃了。这比我预想的要难,我没有时间弄明白。我最近尝试使用一些调试/测试代码。

# 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,8,{'a':1,'b':[1,2]}], 'dave': 'NA', 'john': 18, 'rebecca': 34, 'lvl2':
{'arr': [9,8,{'a':1,'b':[1,2]}], 'dave': 'NA', 'john': 18, 'rebecca': 34, 'lvl3':
{'rebecca': 34, 'dave': 'NA', 'john': 18, 'arr': [9,8,{'a':1,'b':[1,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并试图弄清楚,但似乎没有一种解决方案适用于我的测试用例。

我将只深度复制整个字典并尝试稍后(或不)优化解决方案。

谢谢...

最佳答案

这听起来有点像“请给我 codz”...

在任何情况下,您都需要一个自定义方法,除非您真的想用子类破解可迭代对象的功能。伪代码:

def copy_to_depth(original, depth)
copy = type(original)()
for item in original
if item is iterable and depth > 0
copy + copy_to_depth(item, depth - 1)
else
copy + item
return copy

关于python - 在 python 中,我如何将 dict 深度复制到特定深度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com