【问题标题】:How to optimize the python code having nested lists with conditions in it?如何优化包含带有条件的嵌套列表的python代码?
【发布时间】:2016-12-09 10:35:44
【问题描述】:

我想优化代码至少行数。 我正在遍历 url 列表并解析其中的参数,然后如果在 url 中找到键,则遍历字典的键,然后我将遍历单词列表和参数列表,如果找到匹配项,我正在更新字典。如果对此有任何建议,我将不胜感激。

for url in urls:  # from List of urls 
args = dict(furl(url).args) # Fetch arguments passed in url as list
if args: # if there is any arguments were in  the list
    for j in dashboards1.keys(): # A list of keys dictionary  
        if re.findall(j,url): # Checking if the keys is present in url using regex
            for tm in tg_markets: # list of words
                for a in args: # list of arguments in the url 
                    if tm == a: # if match found .. 
                        dashboards1[j]['tg_count'] += 1 # updating the dictionary 
                        dashboards1[j][tm].append(furl(url).args[tm]) # updating the old dictionary

谢谢

【问题讨论】:

    标签: python python-2.7 performance optimization


    【解决方案1】:

    首先,替换这个:

    for j in dashboards1.keys(): # A list of keys dictionary  
    

    通过

    for j,dashboard in dashboards1.items(): # A list of keys dictionary  
    

    允许将dashboards1[j] 替换为dashboard:抑制了2 个密钥哈希。

    第二,(并非最不重要的!)这个循环是无用的:

            for a in args: # list of arguments in the url 
                if tm == a: # if match found .. 
                    dashboards1[j]['tg_count'] += 1 # updating the dictionary 
                    dashboards1[j][tm].append(furl(url).args[tm])
    

    args 已经是一个字典,因此您正在遍历希望找到tm 的键。做吧:

            if tm in args: # list of arguments in the url 
                dashboard['tg_count'] += 1 # updating the dictionary 
                dashboard[tm].append(furl(url).args[tm]) # updating 
    

    dashboarddashboards[j] 已根据我的第一个建议进行了优化)

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多