[英] List is getting changed when manipulated inside function
我有一个函数,它被设计成递归地在对象数组中查找值,并返回具有类似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()
,但还是不能解决问题.而且,我不需要深度复制,因为它是一个字典数组,而不是一个数组数组