如何优化包含嵌套列表和条件的python代码?
我想优化代码至少行数。 我迭代url列表并解析其中的参数,然后迭代字典的键如果在url中找到键,那么我迭代单词列表和参数列表,如果找到匹配,我更新字典。如果您对此有任何建议,我将不胜感激如何优化包含嵌套列表和条件的python代码?,python,python-2.7,performance,optimization,Python,Python 2.7,Performance,Optimization,我想优化代码至少行数。 我迭代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
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
谢谢首先,请更换此:
for j in dashboards1.keys(): # A list of keys dictionary
借
它允许用仪表板替换仪表板1[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
(dashboard
是dashboards[j]
根据我的第一个建议进行了优化)
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