List在函数内部操作时被更改



我有一个函数,设计用于递归地查找对象数组中的值,并返回具有相似y0的所有变量的字符串。这一切都工作得很好,但是,当我操作数组时,它会操作已输入到其中的数组,尽管我复制了数组以防止此问题。

这意味着当您运行给定的代码时,它将tmp更改为具有不同的文本值。我知道错误是在第26行,当它将BOLD_OBJ["text"]设置为递归函数的输出时,但我不确定为什么考虑它应该操纵数组的副本。

def recursiveScanText(BOLD_OBJ_LIST:list, Y_VALUE: int, output: list):
if BOLD_OBJ_LIST[0]["y0"] == Y_VALUE:
output.append(BOLD_OBJ_LIST[0]["text"])
BOLD_OBJ_LIST.pop(0)
if BOLD_OBJ_LIST == []:
return output
output = recursiveScanText(BOLD_OBJ_LIST, Y_VALUE, output)
return output
else:
return output

def mergeSimilarText(BOLD_OBJ_LIST: list):
"""Merges the objects of a list of objects if they are at a similar (±5) Y coordinate"""
OUTPUT = []
RECURSIVE_SCAN_OUTPUT = []
BOLD_OBJ_LIST = BOLD_OBJ_LIST.copy()

for BOLD_OBJ_INDEX in range(len(BOLD_OBJ_LIST)):
if len(BOLD_OBJ_LIST) > 0 and BOLD_OBJ_INDEX < len(BOLD_OBJ_LIST):
BOLD_OBJ = BOLD_OBJ_LIST[0]

BOLD_CHAR_STRING = recursiveScanText(BOLD_OBJ_LIST, BOLD_OBJ_LIST[BOLD_OBJ_INDEX]["y0"], RECURSIVE_SCAN_OUTPUT)

RECURSIVE_SCAN_OUTPUT = []

BOLD_OBJ["text"] = "".join(BOLD_CHAR_STRING)
OUTPUT.append(BOLD_OBJ)

return OUTPUT

tmp = [
{'y0': 762.064, 'text': '177'}, 
{'y0': 762.064,  'text': '7'}, 
{'y0': 114.8281, 'text': 'Q'}, 
{'y0': 114.8281, 'text': 'u'}, 
{'y0': 114.8281, 'text': 'e'}, 
{'y0': 114.8281, 'text': 's'}, 
{'y0': 114.8281, 'text': 't'}, 
{'y0': 114.8281, 'text': 'i'}, 
{'y0': 114.8281, 'text': 'o'}, 
{'y0': 114.8281, 'text': 'n'}, 
{'y0': 114.8281, 'text': ' '}, 
{'y0': 114.8281, 'text': '1'}, 
{'y0': 114.8281, 'text': '7'}, 
{'y0': 114.8281, 'text': ' '}, 
{'y0': 114.8281, 'text': 'c'}, 
{'y0': 114.8281, 'text': 'o'}, 
{'y0': 114.8281, 'text': 'n'}, 
{'y0': 114.8281, 'text': 't'}, 
{'y0': 114.8281, 'text': 'i'}, 
{'y0': 114.8281, 'text': 'n'}, 
{'y0': 114.8281, 'text': 'u'}, 
{'y0': 114.8281, 'text': 'e'}, 
{'y0': 114.8281, 'text': 's'}, 
{'y0': 114.8281, 'text': ' '}, 
{'y0': 114.8281, 'text': 'o'}, 
{'y0': 114.8281, 'text': 'n'}, 
{'y0': 114.8281, 'text': ' '}, 
{'y0': 114.8281, 'text': 'p'}, 
{'y0': 114.8281, 'text': 'a'}, 
{'y0': 114.8281, 'text': 'g'}, 
{'y0': 114.8281, 'text': 'e'}, 
{'y0': 114.8281, 'text': ' '}, 
{'y0': 114.8281,'text': '9'}]

print(mergeSimilarText(tmp))
print(tmp)

一些注意事项:我已经尝试将BOLD_OBJ_LIST = BOLD_OBJ_LIST.copy()更改为tmp = BOLD_OBJ_LIST.copy(),但仍然无法修复它。而且,我不需要深度拷贝因为它是一个字典数组而不是数组数组

copy使您的列表的浅拷贝,即,如果您在该列表中有可变元素,您只复制引用。

你需要使用deepcopy:

from copy import deepcopy
BOLD_OBJ_LIST = deepcopy(BOLD_OBJ_LIST)

这将递归地创建所有元素的副本。

最新更新