首页 > 解决方案 > 如何优化这个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

标签: pythonperformanceoptimizationexecution-time

解决方案


你有几个不必要的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

推荐阅读