0

我有我想要优化的代码,因为它开始增加音量:(。我想创建一个数组并从他那里调用值,而不是像现在这样为每个对象创建代码:

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'
..........

然后对于文档:

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 更改,我如何在调用它们时进行循环?

4

2 回答 2

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() 
于 2013-02-26T15:55:32.483 回答
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))

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

于 2013-02-26T15:49:19.923 回答