gpt4 book ai didi

python - 将多个列表理解减少为单个语句

转载 作者:太空狗 更新时间:2023-10-30 01:46:20 25 4
gpt4 key购买 nike

寻找减少的列表推导以及更少的循环和内存使用,是否有某种方法可以减少构建最终路径的两个循环,将其转换为单个列表推导?

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_pathshttps_pathspaths)减少到一行,如以下示例结构:

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

最佳答案

添加第二个循环:

['%s://%s' % (scheme, domain) for scheme in ('http', 'https') for domain in domains]

这会首先构建所有 http url,然后是 https url,就像您的原始代码一样。

关于python - 将多个列表理解减少为单个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com