gpt4 book ai didi

python - 如何优化具有带条件的嵌套列表的Python代码?

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:14 25 4
gpt4 key购买 nike

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

谢谢

最佳答案

首先,替换它:

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 个 key 哈希。

其次,(而且并非最不重要的!!)这个循环是无用的:

        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],已根据我的第一个建议进行了优化)

关于python - 如何优化具有带条件的嵌套列表的Python代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41058409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com