重复For循环以获取更大的json数据,并且在Python中没有重复数据

0s0u357o  于 2022-12-30  发布在  Python
关注(0)|答案(2)|浏览(88)

我尝试重复json文件10次,每次迭代中在名为“ProcessGuid”的元素处添加1~10,代码如下

import json
file = open("D:/Test/test.json",'r',encoding='utf-8')
papers = []
for line in file.readlines():
    dic = json.loads(line)
    papers.append(dic)
    
result_int = papers
string_name = list(map(str, range(1,10)))
    
for element in string_name:
    result = []
    result = result_int
    processlist = []
    for i in range(len(result)):
        (result[i])['Event']['EventData']['ProcessGuid'] = str((result[i])['Event']['EventData']['ProcessGuid'])+element
    
    with open("D:/Test/process_"+str(element)+".json", 'w', encoding ='utf8') as json_file:
        json.dump(result, json_file, ensure_ascii = False)

我认为每次重复中的数据结果应该是这样的(假设ProcessGuid的原始数据元素是Hello)

1st repeat : ProcessGuid = Hello1
2nd repeat : ProcessGuid = Hello2
3rd repeat : ProcessGuid = Hello3
...
10th repeat : ProcessGuid = Hello10

但结果如下

1st repeat : ProcessGuid = Hello1
2nd repeat : ProcessGuid = Hello12
3rd repeat : ProcessGuid = Hello123
...
10th repeat : ProcessGuid = Hello12345678910

我哪里错了?谢谢。

zkure5ic

zkure5ic1#

你一遍又一遍地覆盖result_int。
How do I clone a list so that it doesn't change unexpectedly after assignment?
变更:

result = list(result_int)
t1qtbnec

t1qtbnec2#

对于每个element,代码将追加到相同的值。如果您只想将每个element追加到原始值一次,则可以先保存原始值:

base_values = [str(paper['Event']['EventData']['ProcessGuid']) for paper in papers]

for element in string_name:
    for i, paper in enumerate(papers):
        paper['Event']['EventData']['ProcessGuid'] = base_values[i] + element
    
    with open("D:/Test/process_" + str(element) + ".json", 'w', encoding ='utf8') as json_file:
        json.dump(papers, json_file, ensure_ascii = False)

相关问题