寻找减少列表的压缩,减少循环和内存使用,有一些方法可以减少两个循环来构建最终路径,将其转换为单个列表压缩?
def build_paths(domains):
http_paths = ["http://%s" % d for d in domains]
https_paths = ["https://%s" % d for d in domains]
paths = []
paths.extend(http_paths)
paths.extend(https_paths)
return paths
在这种情况下,预期结果是优化列表压缩,从三个列表引用(http_paths
,https_paths
,paths
)减少到一行,如下例所示结构:
def build_paths(domains):
return [<reduced list comprehesion> for d in domains]
在这两种情况下,运行以下测试:
domains = ["www.ippssus.com",
"www.example.com",
"www.mararao.com"]
print(build_paths(domains))
预期输出,与列表顺序无关:
< ['http://www.ippssus.com', 'http://www.example.com', 'http://www.tetsest.com', 'https://www.ippssus.com', 'https://www.example.com', 'https://www.tetsest.com']
答案 0 :(得分:14)
添加第二个循环:
['%s://%s' % (scheme, domain) for scheme in ('http', 'https') for domain in domains]
首先构建所有http
网址,然后构建https
网址,就像您的原始代码一样。