python - 如何优化这个python代码?我需要改进它的运行时间
问题描述
我想优化这个过滤功能。它在两个列表中搜索:一个是类别,一个是标签。这就是为什么运行此功能需要很长时间的原因。
def get_percentage(l1, l2, sim_score):
diff = intersection(l1, l2)
size = len(l1)
if size != 0:
perc = (diff/size)
if perc >= sim_score:
return True
else:
return False
def intersection(lst1, lst2):
return len(list(set(lst1) & set(lst2)))
def filter_entities(country, city, category, entities, entityId):
valid_entities = []
tags = get_tags(entities, entityId)
for index, i in entities.iterrows():
if i["country"] == country and i["city"] == city:
for j in i.categories:
if j == category:
if(get_percentage(i["tags"], tags, 0.80)):
valid_entities.append(i.entity_id)
return valid_entities
解决方案
你有几个不必要的for
循环和if
检查在那里你可以删除,你绝对应该利用df.loc
从你的数据框中选择元素(假设entities
是Pandas 数据框):
def get_percentage(l1, l2, sim_score):
if len(l1) == 0:
return False # shortcut this default case
else:
diff = intersection(l1, l2)
perc = (diff / len(l1))
return perc >= sim_score # rather than handling each case separately
def intersection(lst1, lst2):
return len(set(lst1).intersection(lst2)) # almost twice as fast this way on my machine
def filter_entities(country, city, category, entities, entityId):
valid_entities = []
tags = get_tags(entities, entityId)
# Just grab the desired elements directly, no loops
entity = entities.loc[(entities.country == county) &
(entities.city == city)]
if category in entity.categories and get_percentage(entity.tags, tags, 0.8):
valid_entities.append(entity.entity_id)
return valid_entities
很难确定这会有所帮助,因为我们无法真正运行您提供的代码,但这应该会消除一些低效率并利用 Pandas 中可用的一些优化。
根据您的数据结构(即,如果您在entity
上面有多个匹配项),您可能需要对上面的最后三行执行类似的操作:
for ent in entity:
if category in ent.categories and get_percentage(ent.tags, tags, 0.8):
valid_entities.append(ent.entity_id)
return valid_entities
推荐阅读
- html - 我想进一步拉伸文本,但是,“text-align: justify”并没有做我想要的
- dynamics-crm - 在 Dynamics 365 门户上更改页面标题
- c - 使用变量声明/定义实现弱链接是否可移植?
- python - Discord Bot Python 3.6 导入命令时出错
- inno-setup - Inno Setup 在安装过程中有时无法更改文件
- apache-camel - 如何读取同一目录中的两对文件并发送到同一个骆驼交易所?
- php - Json 页面和发布请求 PHP
- django - DJANGO: ValidationError ["'journals__Start_Date' 值的日期格式无效。它必须是 YYYY-MM-DD 格式。"]
- django - Django REST Swagger 使用 permission_classes=[IsAuthenticated] 隐藏 ModelViewSet
- javascript - 带有 CSS 的循环样式