1 回答
TA贡献2011条经验 获得超2个赞
我设法将所有内容合并到一个元组中,然后使用 对其进行排序natsort,然后将其“缝合”在一起,从而成功地缝合了一个解决方案。
这是代码:
import json
from natsort import natsort_keygen
natsort_key = natsort_keygen()
Data_JSON = 'data.json'
BATCH_NAME = 'NON_BATCH'
file_names = []
image_locations = []
quantities = []
description = []
checkmarked = []
materials = []
def merge(*args):
return [(args[0][i], args[1][i], args[2][i], args[3][i], args[4][i], args[5][i]) for i in range(len(args[0]))]
with open(Data_JSON) as file:
Data_JSON_Contents = json.load(file)
for item in Data_JSON_Contents[0][BATCH_NAME]:
file_names.append(item['fileName'][0])
image_locations.append(item['imgLoc'][0])
quantities.append(item['quantity'][0])
description.append(item['description'][0])
checkmarked.append(item['checked'][0])
materials.append(item['material'][0])
merged = sorted(merge(file_names, image_locations, quantities,
description, checkmarked, materials), key=natsort_key)
for i, j in enumerate(file_names):
Data_JSON_Contents[0][BATCH_NAME].pop(0)
Data_JSON_Contents[0][BATCH_NAME].append({
'fileName': [merged[i][0]],
'imgLoc': [merged[i][1]],
'quantity': [int(merged[i][2])],
'description': [merged[i][3]],
'checked': [merged[i][4]],
'material': [merged[i][5]]
})
with open(Data_JSON, mode='w+', encoding='utf-8') as file:
json.dump(Data_JSON_Contents, file,
ensure_ascii=True, indent=4)
无论如何,它都不是简洁的代码,也不是经过优化的,但它是有效的,如果有人有一些建议可以让它变得更好、更“时尚”,我会非常乐意使用它。
添加回答
举报