如何优化这个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循环,如果你可以删除那里的检查,你绝对应该利用df.loc
从数据框中选择元素(假设实体是一个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中可用的一些优化.
根据您的数据结构(即如果您在上面的实体中有多个匹配项),您可能需要对上面的最后三行执行类似的操作:
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
标签:python,optimization,execution-time,performance 来源: https://codeday.me/bug/20190701/1346653.html