You need to enable JavaScript to run this app. Python中无需重复代码输出包含列表名及内容的格式化字符串的方法
优惠活动
大模型
产品
解决方案
定价
更多

Python中无需重复代码输出包含列表名及内容的格式化字符串的方法

解决方案

方法1:用字典统一存储列表(最推荐)

把所有列表存入同一个字典,键为列表名称,值为列表本身,只需遍历字典即可完成批量输出,后续新增列表只需在字典中新增键值对,无需修改输出逻辑。

# 统一存储所有列表
all_lists = {
    "greetings": ["hello", "hi"],
    "wishes": ["happy bday", "merry Xmas"],
    "pets": ["dog", "cat"]
    # 剩余7个列表直接按格式添加在这里即可
}

# 批量输出
for list_name, list_content in all_lists.items():
    content_str = ", ".join(list_content)
    print(f'"Content of {list_name}: {content_str}"')

方法2:动态获取已有变量(适合已提前定义好列表变量的场景)

如果你已经提前定义好了10个列表变量,不想重构为字典结构,可以把列表名存入字符串列表,通过globals()动态获取变量值完成输出:

# 已经提前定义好的列表变量
greetings = ["hello", "hi"]
wishes = ["happy bday", "merry Xmas"]
pets = ["dog", "cat"]

# 把需要输出的列表名存为字符串列表
target_lists = ["greetings", "wishes", "pets"]

for name in target_lists:
    content_str = ", ".join(globals()[name])
    print(f'"Content of {name}: {content_str}"')

两种方法的输出结果都和你给出的示例完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 00:12:02