Skip to main content
 首页 » 编程设计

python之返回网站状态代码作为键和网站作为值的字典之py

2025年05月04日14jyk

嘿伙计们,我需要一些关于这个问题的指导(.py noobie)

所以我有一个具有不同状态代码的网站列表:

url_list=["http://www.ehow.com/foo-barhow_2323550_clean-coffee-maker-vinegar.html", 
          "http://www.google.com", 
          "http://livestrong.com/register/confirmation/", 
          "http://www.facebook.com", 
          "http://www.youtube.com"] 

我要返回的是一个字典,它将网站的状态代码作为键返回,关联的网站作为值返回。类似的东西:

result= {"200": ["http://www.google.com", 
                 "http://www.facebook.com", 
                 "http://www.youtube.com"],  
         "301": ["http://livestrong.com/register/confirmation/"], 
         "404": ["http://www.ehow.com/foo-barhow_2323550_clean-coffee-maker-vinegar.html"]} 

我现在所拥有的:

获取状态码的函数:

def code_number(url): 
    try: 
        u = urllib2.urlopen(url) 
        code = u.code 
    except urllib2.HTTPError, e: 
        code = e.code 
    return code 

一个函数应该返回字典但不起作用 - 我被卡住的部分。基本上我不知道如何让它在相同的状态代码中插入超过 1 个 url

result={} 
def get_code(list_of_urls): 
    for n in list_of_urls: 
        code = code_number(n) 
        if n in result: 
            result[code] = n 
        else: 
            result[code] = n 
    return result 

有什么想法吗?!谢谢

请您参考如下方法:

collections.defaultdict 让这变得轻而易举:

import collections 
 
def get_code(list_of_urls): 
    result = collections.defaultdict(list) 
    for n in list_of_urls: 
        code = code_number(n) 
        result[code].append(n) 
    return result 

不确定为什么将 result 作为全局变量,因为无论如何它都会作为函数的结果返回(避免使用全局变量,除非确实不可或缺……局部变量不仅在结构上更好,而且速度更快访问)。

无论如何,collections.defaultdict 实例 result 将自动调用 list 参数,从而生成一个空列表,以初始化任何条目result[n] 在编制索引时还不存在;所以你可以直接附加到条目而不需要检查它以前是否存在。 那是 super 方便的想法!

如果出于某种原因你想要一个普通的 dict 作为结果(虽然我想不出任何合理的理由需要它),只需 return dict(result) 将 defaultdict 转换为普通的 dict。