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

使用pprint仍单行输出对象列表,如何转为多行可读格式?

解决response.choices等对象列表多行可读打印问题

当你用print或pprint直接打印API返回的对象列表时,因为对象默认的__repr__是单行格式,输出会挤在一起。可以用以下几种方法实现多行可读排版:

方法一:转为字典后用pprint打印

多数API返回的对象(比如OpenAI的ChatCompletion对象)都提供了dict()方法,能将对象转为嵌套字典。pprint处理字典时会自动分层换行:

from pprint import pprint

# 转换response.choices为字典列表
choices_dict = [choice.dict() for choice in response.choices]
pprint(choices_dict)

方法二:用json模块格式化输出

将字典转为带缩进的JSON字符串,不仅换行清晰,还能更好地展示嵌套结构:

import json

choices_dict = [choice.dict() for choice in response.choices]
# indent=2控制缩进空格数,ensure_ascii=False支持中文显示
print(json.dumps(choices_dict, indent=2, ensure_ascii=False))

方法三:自定义对象的字符串表示(进阶)

如果需要对打印格式做更个性化的控制,可以封装对象并自定义__repr__方法,利用pprint.pformat实现换行:

from pprint import pformat

class FormattedChoice:
    def __init__(self, original_choice):
        self.data = original_choice
    
    def __repr__(self):
        return pformat(vars(self.data), indent=2)

# 包装后打印
formatted_choices = [FormattedChoice(c) for c in response.choices]
print(formatted_choices)

内容的提问来源于stack exchange,提问作者Marek Gwóźdź

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:32:26