我有一个包含360万条记录的companies.json文件(每条记录都包含一个id & vat编号)和一个包含76.000条记录(+- 20属性)的event.json文件。我编写了一个脚本,执行以下步骤:
number
H 19事件是否具有companyID,循环遍历360万条记录以找到匹配的公司ID。<>H 210H 111检查匹配的公司记录是否有一个带有增值税编号的VAT companyID,并添加一个companyIDIsVat boolean.
剧本运行良好,但要花6-7个小时才能完成。有办法加快速度吗?
当前脚本
import json
counter = 0;
with open('companies.json', 'r') as companiesFile:
with open('events.json', 'r') as eventsFile:
events = json.load(eventsFile)
companies = json.load(companiesFile)
for index, event in enumerate(events):
print('Counter: ' + str(index))
if 'status' in event:
if(event['status'] == 'new'):
if 'companyID' in event:
for company in companies:
if(event['companyID'] == company['_id']):
if 'vat' in company:
event['companyID'] = company['vat']
event['companyIDIsVat'] = 1
counter = counter + 1
print('Found matches: ' + str(counter))
with open('new_events.json', 'w', encoding='utf-8') as f:
json.dump(events, f, ensure_ascii=False, indent=4)发布于 2022-04-08 07:57:02
所以,问题是你要反复搜索整个公司的名单。但是列表对于搜索效率很低,因为在这里,您必须执行线性搜索,即O(N)。但如果你用的话你可以做一个固定时间的搜索。假设你是,company['_id']是唯一的。基本上,你想在你的ID上索引。对于固定时间的查找,使用字典,即映射( CPython中的散列映射,以及可能的每个python实现):
import json
counter = 0
with open('companies.json', 'r') as companiesFile:
with open('events.json', 'r') as eventsFile:
events = json.load(eventsFile)
companies = {
c["_id"]: c for c in json.load(companiesFile)
}
for index, event in enumerate(events):
print('Counter: ' + str(index))
if 'status' in event:
if (
event['status'] == 'new'
and 'companyID' in event
and event['companyID'] in companies
):
company = companies[event['companyID']]
if 'vat' in company:
event['companyID'] = company['vat']
event['companyIDIsVat'] = 1
counter = counter + 1
print('Found matches: ' + str(counter))
with open('new_events.json', 'w', encoding='utf-8') as f:
json.dump(events, f, ensure_ascii=False, indent=4)这是对脚本的最小修改。
您可能应该将companies.json保存在适当的结构中。
同样,它假设公司在ID上是唯一的。如果没有,那么您可以使用列表字典,而且只要没有很多重复ID,它的速度就应该更快。
https://stackoverflow.com/questions/71793357
复制相似问题