加速python中的字典(列表)处理

时间:2017-01-27 13:32:13

标签: python dictionary

我在python中有一个大小约250k的字典列表(即列表中的250k字典),我尝试处理如下所示。目的是clean up字典并在结尾返回一个iterable。所以,我有这样的事情:

def check_qs(dict_list_in):
    try:
        del_id=[]
        for i in dict_list_in:
            tmp=i["get_url"][0]
            if i["from"][0]=="var0":
                try:
                    URLValidator()(tmp)
                except:
                    del_id.append( i["id"] )
            elif i["from"][0]=="var1":
                try:
                    URLValidator()( tmp.split("\"")[1] )
                except:
                    del_id.append( i["id"] )
            elif i["from"][0]=="var2":
                try:
                    URLValidator()( tmp.split("\'")[1] )
                except:
                    del_id.append( i["id"] )
            else:
                del_id.append( i["id"] )
            gc.collect()
        result = filter(lambda x: x['id'] not in del_id,dict_list_in)
        return result
     except:
        return dict_list_in

我上面正在做的是检查列表中的每个字典是否存在某些情况,如果是fails,我会得到id,然后使用filter删除特定的字典从列表中。

目前,这需要很长时间才能运行 - 我想知道是否有任何明显的优化我错过了。我认为目前上面的代码太天真了。

1 个答案:

答案 0 :(得分:0)

我做了一些改变。我将验证实例放在循环之外,这样您就不必每次都初始化它。如果每次都需要实例化,只需将其移动到try accept块中即可。我还更改了删除原始列表中的项目,将项目附加到您想要的新列表,从而无需过滤器。我还将验证移出了if语句,这样如果你点击else语句,你就不必运行验证。看看if语句的逻辑,它和你的一样。您似乎正在使用django,但如果您没有将except更改为except Exception

from django.core.exceptions import ValidationError

def check_qs(dict_list_in):
    new_dict_list = []
    validate = URLValidator()

    for i in dict_list_in:
        test_url = i["get_url"][0]
        if i["from"][0] == "var0":
            pass
        elif i["from"][0] == "var1":
            test_url = test_url.split("\"")[1]
        elif i["from"][0] == "var2":
            test_url = test_url.split("\'")[1]
        else:
            continue

        try:
            validate(test_url)
        # If you aren't using django you can change this to 'Exception'
        except ValidationError:
            continue
        new_dict_list.append(i)

    return new_dict_list
相关问题