我需要帮助创建类似循环的东西来缩短我的代码。目前我有:
将数据从JSON字典写入适当文件的代码:
file_01 = f'{root_path}/{output}/{file_name_01}.{json_ext}'
file_02 = f'{root_path}/{output}/{file_name_02}.{json_ext}'
file_03 = f'{root_path}/{output}/{file_name_03}.{json_ext}'
file_04 = f'{root_path}/{output}/{file_name_04}.{json_ext}'
file_05 = f'{root_path}/{output}/{file_name_05}.{json_ext}'
file_06 = f'{root_path}/{output}/{file_name_06}.{json_ext}'
file_07 = f'{root_path}/{output}/{file_name_07}.{json_ext}'
json_dic_01 = [{"test": "test", "test1" : "test1"}]
json_dic_02 = [{"test": "test", "test1" : "test1"}]
json_dic_03 = [{"test": "test", "test1" : "test1"}]
json_dic_04 = [{"test": "test", "test1" : "test1"}]
json_dic_05 = [{"test": "test", "test1" : "test1"}]
json_dic_06 = [{"test": "test", "test1" : "test1"}]
json_dic_07 = [{"test": "test", "test1" : "test1"}]
def save_to_json(json_dic, data_to_save):
with open(data_to_save, 'w', encoding= utf_8) as json_file:
json.dump(json_dic, json_file, ensure_ascii= False, indent=4, sort_keys= True)
save_to_json(json_dic_01, file_01)
save_to_json(json_dic_02, file_02)
save_to_json(json_dic_03, file_03)
save_to_json(json_dic_04, file_04)
save_to_json(json_dic_05, file_05)
save_to_json(json_dic_06, file_06)
save_to_json(json_dic_07, file_07)
现在我想通过使用类似循环的东西来减少save_to_json()
函数的迭代次数
我创建了json_dics
的列表:
json_dics = [json_dic_01, json_dic_02, json_dic_03, json_dic_04, json_dic_05, json_dic_06, json_dic_07]
和fnames
:
fnames = [file_01, file_02, file_03, file_04, file_05, file_06, file_07]
我的愿景是:
for dic in json_dics:
take the assigned fname and save
如有任何帮助和建议,我将不胜感激。
2条答案
按热度按时间2uluyalo1#
您可以使用zip()函数来迭代两个json_dics列表,因为这会有所帮助。
1yjd4xko2#
编辑:您也可以为第一行创建一个循环:
假设您有列表
filenames
中的每个file_name_xx
。您可以对json_dic执行相同的操作