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

如何将两个Python列表的元素组合生成指定格式的字符串列表

实现方法

核心逻辑是遍历List2中的每一组二元数值,按顺序和List1的三个固定字符串拼接即可,最简洁的实现是用列表推导式:

List1 = ['foo', 'bar', '.txt']
List2 = [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

# 核心拼接代码
output = [f"{List1[0]}{a}{List1[1]}{b}{List1[2]}" for a, b in List2]

运行后输出的output完全符合预期结果:

['foo1bar3.txt', 'foo1bar4.txt', 'foo1bar5.txt', 'foo2bar3.txt', 'foo2bar4.txt', 'foo2bar5.txt']

如果需要适配Python 3.6之前不支持f-string的版本,可以替换为format写法:

output = ["{0}{1}{2}{3}{4}".format(List1[0], a, List1[1], b, List1[2]) for a, b in List2]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:27:00