我怎样才能让它变得动态

时间:2013-02-26 15:46:34

标签: python loops for-loop python-2.7 urllib2

我有这个我想要优化的代码,因为它启动它以获得音量:(。我想创建一个数组并从他那里调用值,而不是像我现在所做的那样为每个对象创建代码:

post_data_groups = {'profile': '46', 'clear': 'Remove+Avatar'}
post_data_documents = {'folder1': '30', 'remove': 'Delete+Documents'}

urlAdmin_groups = 'http://site.com/management.php?Category=6&uid=196'
urlModerator_groups = 'http://site.com/management.php?Category=6&uid=197'
..........

然后是Documents:

urlAdmin_documents = 'http://site.com/management.php?Category=3&uid=196'
urlModerator_documents = 'http://site.com/management.php?Category=3&suid=197'
.... and so on
data_groups= urllib.urlencode(post_data_groups)
data_documents= urllib.urlencode(post_data_documents)

然后我这样打电话给他们:

response = opener.open(urlAdmin_groups, data_groups)
response = opener.open(urlAdmin_documents, data_documents)
........... and so on
the_page = response.read()

我是如何在调用它们时循环的,因为只有类别和uid发生了变化?

2 个答案:

答案 0 :(得分:3)

基本上它是map内置函数的一个很好的用例:

url = 'http://site.com/management.php?Category={cat}&uid={uid}'
cat_uids = [ (3,196), (3,197), ... ] # read thos from config file or...
urls = [ url%cat_uid for cat_uid in cat_uids ]
responses = map(opener.open, urls)
pages = map(response_class.read,responses) # where response_class is the class returned by open() 

答案 1 :(得分:2)

使用字符串作为模板:

url = 'http://site.com/management.php?Category={cat}&uid={uid}'

然后你可以使用.format()字符串方法来填充插槽:

response = opener.open(url.format(cat=3, uid=196), data))
the_page = response.read()

你必须将它扩展为使用循环,在那里迭代某些然后提供类别和UID,但你明白了。也许映射可行:

groups = {
    Admin: {'cat': 3, 'uid': 196},
    ...
}

for groupname, urlvalues in groups.iteritems():
    response = opener.open(url.format(**urlvalues), data_groups))

其中**格式将字典应用为一组关键字参数;使用.format(**urlvalues)实际上转换为.format(cat=urlvalues['cat'], uid=urlvalues['uid'])