如何优化包含嵌套列表和条件的python代码?

2024-10-02 00:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想优化代码至少行数。 我迭代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

谢谢


Tags: oftheinurl列表for参数dictionary
1条回答
网友
1楼 · 发布于 2024-10-02 00:22:41

首先,将其替换为:

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

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

它允许用dashboard替换dashboards1[j]:抑制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],我的第一个建议已经对其进行了优化)

相关问题 更多 >

    热门问题