You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何通过双f-string替换批量生成URL列表

实现方案

你需要的是两个列表的笛卡尔积遍历(即所有元素两两组合),有两种常用实现方式:

方法1:嵌套for循环(最直观,无需额外导入包)

直接在原有外层循环的基础上,新增一层遍历tag_names的内层循环即可,f-string支持同时放多个变量替换:

tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']

for domain in domain_names:
    for tag in tag_names:
        print(f'www.{domain}.com/{tag}')

运行后直接输出你需要的所有结果。

方法2:使用itertools.product(适合多列表组合,代码更简洁)

如果后续需要扩展到更多列表组合的场景,用Python标准库的itertools.product可以避免写多层嵌套循环:

from itertools import product

tag_names = ['business', 'science', 'technology']
domain_names = ['bbc', 'cnn', 'nytimes']

for domain, tag in product(domain_names, tag_names):
    print(f'www.{domain}.com/{tag}')

两种方法的输出完全一致,都可以满足需求。

内容的提问来源于stack exchange,提问作者codedancer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:48:01