本文介绍如何用 python 读取 json 文件,提取特定键值(如 date 和 count),生成格式化字符串列表,并将其合并为单个含换行符的字符串,以便通过一次 `print()` 输出多行内容。
要实现“将每条记录按指
定格式输出在不同行”,核心在于:将多个字符串元素组合成一个带换行符(\n)分隔的单一字符串,而非逐行调用 print() 或仅生成列表却未拼接。
以下是完整、可运行的解决方案:
import json
# 1. 加载 JSON 文件
with open('file.json', 'r', encoding='utf-8') as file:
data = json.load(file)
# 2. 构建每行格式化字符串(推荐使用 f-string 提升可读性)
new_list = [f'Date --> {item["date"]}, Remaining counts --> {item["count"]}' for item in data]
# 3. 使用 '\n'.join() 将列表合并为单个换行分隔的字符串
new_var = '\n'.join(new_list)
# 4. 一次性打印全部内容(含标题)
print(f'This is our data:\n{new_var}')✅ 输出效果示例:
This is our data: Date --> 1402/11/03, Remaining counts --> 5 Date --> 1402/11/04, Remaining counts --> 2 Date --> 1402/11/05, Remaining counts --> 4 ...
? 关键说明与注意事项:
掌握 join() 与列表推导式的组合,是 Python 中处理批量格式化输出的常用范式——简洁、清晰、符合 Pythonic 风格。