嘿伙计我需要一些关于这个问题的指导(.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"]
Run Code Online (Sandbox Code Playgroud)
我想要返回的是一个字典,它将网站的状态代码作为关键字返回,并将关联的网站作为值返回.像这样的东西:
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"]}
Run Code Online (Sandbox Code Playgroud)
我到现在为止:
获取状态代码的函数:
def code_number(url):
try:
u = urllib2.urlopen(url)
code = u.code
except urllib2.HTTPError, e:
code = e.code
return code
Run Code Online (Sandbox Code Playgroud)
一个函数应该返回字典但不工作 - 我被卡住的部分.基本上我不知道如何使它插入相同的状态代码超过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
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?!谢谢
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
Run Code Online (Sandbox Code Playgroud)
不知道为什么你有result一个全局,因为它无论如何都是作为函数的结果返回的(避免全局除非真正必不可少......本地人不仅是一种结构上更好的方法,而且访问速度更快).
无论如何,collections.defaultdict实例result将自动调用list参数,从而创建一个空列表,以初始化result[n]索引时尚未存在的任何条目; 所以你可以只是附加到条目而不需要检查它是否以前存在. 那是超级方便的想法!
如果由于某种原因你想要一个普通dict的结果(虽然我想不出任何合理的理由需要),只是return dict(result)将其defaultdict转换为平原dict.