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

求类似R语言str()函数的Python嵌套对象摘要工具

Great question! R's str() is such a handy tool for getting a concise, nested overview of objects, and it's totally fair to want something similar in Python. While there's no exact 1:1 built-in equivalent, there are a few tools that hit both your requirements—readable structured output and truncated representative content for long objects. Let's break them down:

1. Rich Library

Rich is a powerful, modern formatting library that's perfect for this use case. It handles nested objects seamlessly, automatically truncates long lists/strings to show representative content, and adds color-coding for even better readability.

First, install it:

pip install rich

Then use its pretty-printing tools:

from rich.pretty import pprint

# Example nested object with long content
nested_data = {
    "metadata": {"type": "experiment", "id": "exp-123"},
    "results": {
        "values": [i for i in range(150)],  # Long list
        "metrics": {"accuracy": 0.92, "precision": 0.89}
    }
}

# Print with truncation for long lists
pprint(nested_data, max_length=10)

This will output a nicely indented, nested view where the long values list is truncated to show the first 5, ..., and last 5 elements, plus the total length—exactly the kind of concise overview you want.

2. devtools' pretty() Function

The devtools library has a pretty() function that's designed to mimic the concise, structured output of R's str(). It lets you control depth and truncation directly.

Install it first:

pip install devtools

Usage example:

from devtools import pretty

# A deeply nested list with long sublists
deep_list = [[i*j for i in range(30)] for j in range(10)]

# Print with depth limit and truncation
pretty(deep_list, depth=3, truncate=10)

This will show the nested structure, truncate long sublists, and keep the output compact but informative—super close to R's str() in style.

3. Custom Recursive Function (No Third-Party Dependencies)

If you prefer not to install external libraries, you can write a simple recursive function to replicate the core behavior of str(). Here's a basic version that handles lists, dicts, and primitive types:

def str_like(obj, indent=0, max_display=10):
    indent_prefix = "  " * indent
    
    if isinstance(obj, list):
        print(f"{indent_prefix}List ({len(obj)} elements):")
        # Truncate long lists
        if len(obj) > max_display:
            displayed_items = obj[:max_display//2] + ["..."] + obj[-max_display//2:]
        else:
            displayed_items = obj
        for item in displayed_items:
            str_like(item, indent + 1, max_display)
    
    elif isinstance(obj, dict):
        print(f"{indent_prefix}Dict ({len(obj)} keys):")
        # Truncate long key-value pairs
        items = list(obj.items())
        if len(items) > max_display:
            displayed_items = items[:max_display//2] + [("...", "...")] + items[-max_display//2:]
        else:
            displayed_items = items
        for key, value in displayed_items:
            print(f"{indent_prefix}  {repr(key)}:")
            str_like(value, indent + 2, max_display)
    
    else:
        # Handle primitive types (strings, numbers, booleans)
        print(f"{indent_prefix}{repr(obj)}")

# Test with a complex object
test_obj = {
    "user": "alice",
    "activity": [f"action_{i}" for i in range(75)],
    "settings": {"theme": "dark", "notifications": True, "preferences": {"language": "en", "timezone": "UTC"}}
}

str_like(test_obj)

You can extend this function to support more object types (like pandas DataFrames, numpy arrays) as needed.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:07:29