我有大约 100,000 个具有以下结构的 JSON 文件:
{'images': [<list of dicts>],
'annotations': [<list of dicts>],
'videos': [<list of dicts>]}
每个 JSON 的大小各不相同,但平均约为 2MB。我有很多 RAM (488GB),但似乎仍然只能容纳其中大约 70% 到内存中。
Python 中将这些组合到单个 JSON 文件中的最快方法是什么(使用相同的三个键,其中列表组合成单个大列表)?
我考虑过对所有这些进行 3 次循环(每个键一个循环)并附加到一个文件,但这会非常慢。我不确定是否存在更好的方法。
以下是我尝试一次加载它们的方法(速度会变慢,然后在完成之前失败):
from glob import glob
import json
from tqdm import tqdm
full = {
'videos': [],
'images': [],
'annotations': []
}
for fp in tqdm(glob('coco_parts/*.json')):
with open(fp, 'r') as f:
single = json.load(f)
full['videos'] += single['videos']
full['images'] += single['images']
full['annotations'] += single['annotations']
最佳答案
我没有足够的声誉来发表评论,所以我会将其留在这里作为答案。
事实上,您无法将这些文件存储在内存中,尽管这对您的电脑来说应该不是问题,可能是由于您正在使用的 python 对象增加了开销:
{'images': [<list of dicts>],
'annotations': [<list of dicts>],
'videos': [<list of dicts>]}
一个想法可能是改用其他东西,比如单个字符串(保留正确的 JSON 结构)或使用 pandas/numpy,就像这些文章建议的那样:article , article .
关于python - 合并许多内存不足的 JSON 文件的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63971691/