在 Python 中生成包含两个 f 字符串替换的 url 列表
Generate a list of urls with two f-string substitutions in Python
我正在尝试通过循环两个单词列表来生成 url 列表。我可以通过 f-string 做一个,但我不太确定如何同时做两个。有什么建议吗?
tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']
for domain in domain_names:
print(f'www.{domain}.com/{tag}')
预期结果
www.bbc.com/business
www.bbc.com/science
www.bbc.com/technology
www.cnn.com/business
www.cnn.com/science
www.cnn.com/technology
www.nytimes.com/business
www.nytimes.com/science
www.nytimes.com/technology
您可以使用 itertools.product
和列表理解:
import itertools
tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']
[f'www.{domain}.com/{tag}' for domain, tag in itertools.product(domain_names, tag_names)]
输出:
['www.bbc.com/business',
'www.bbc.com/science',
'www.bbc.com/technology',
'www.cnn.com/business',
'www.cnn.com/science',
'www.cnn.com/technology',
'www.nytimes.com/business',
'www.nytimes.com/science',
'www.nytimes.com/technology']
或者使用嵌套循环:
tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']
print([f'www.{domain}.com/{tag}' for domain in domain_names for tag in tag_names])
输出:
['www.bbc.com/business',
'www.bbc.com/science',
'www.bbc.com/technology',
'www.cnn.com/business',
'www.cnn.com/science',
'www.cnn.com/technology',
'www.nytimes.com/business',
'www.nytimes.com/science',
'www.nytimes.com/technology']
res=zip(tag_names,domain_names)
for i in res:
print(f'www.{i[1]}.com/{i[0]}')
我正在尝试通过循环两个单词列表来生成 url 列表。我可以通过 f-string 做一个,但我不太确定如何同时做两个。有什么建议吗?
tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']
for domain in domain_names:
print(f'www.{domain}.com/{tag}')
预期结果
www.bbc.com/business
www.bbc.com/science
www.bbc.com/technology
www.cnn.com/business
www.cnn.com/science
www.cnn.com/technology
www.nytimes.com/business
www.nytimes.com/science
www.nytimes.com/technology
您可以使用 itertools.product
和列表理解:
import itertools
tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']
[f'www.{domain}.com/{tag}' for domain, tag in itertools.product(domain_names, tag_names)]
输出:
['www.bbc.com/business',
'www.bbc.com/science',
'www.bbc.com/technology',
'www.cnn.com/business',
'www.cnn.com/science',
'www.cnn.com/technology',
'www.nytimes.com/business',
'www.nytimes.com/science',
'www.nytimes.com/technology']
或者使用嵌套循环:
tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']
print([f'www.{domain}.com/{tag}' for domain in domain_names for tag in tag_names])
输出:
['www.bbc.com/business',
'www.bbc.com/science',
'www.bbc.com/technology',
'www.cnn.com/business',
'www.cnn.com/science',
'www.cnn.com/technology',
'www.nytimes.com/business',
'www.nytimes.com/science',
'www.nytimes.com/technology']
res=zip(tag_names,domain_names)
for i in res:
print(f'www.{i[1]}.com/{i[0]}')