提问人:SapereAude 提问时间:11/15/2023 最后编辑:SapereAude 更新时间:11/17/2023 访问量:52
在 IDLE 中,限制 pprint 调用显示的行数的最简单方法是什么?
In IDLE, what is the simplest way to limit the number of lines displayed by a pprint call?
问:
我正在使用 Python 中的大型嵌套字典,并希望在 IDLE 中快速检查它们的结构。pprint
模块很好地显示了这种结构,但由于变量的大小,导致 IDLE 挂起。有没有一种简单的方法来限制打印的行数,或者类似地限制在每个结构级别上显示的键值对的数量?(我可能在这里遗漏了一些明显的东西。pprint
值得注意的是,似乎有一个 reprlib 模块是为了在一定数量的字符后截断输出的类似目标而制作的。但是,它没有以可读的方式显示大型嵌套词典的结构,因此该模块对于我的目的来说似乎是不切实际的。print
print
答:
0赞
Seaver
11/15/2023
#1
您是否尝试过通过设置参数或设置来减少嵌套?查看 https://docs.python.org/3/library/pprint.htmldepth
compact=True
评论
0赞
SapereAude
11/15/2023
是的,不幸的是,这些参数都不适用于此目的。我想查看完全深度的嵌套字典结构(在一种情况下仅由 depth=3 给出)。compact=True 似乎对我的输出完全没有影响。原则上,当宽度允许时,此参数设置会将许多项目放在一行上,但就我而言,这既会使输出更加拥挤,又不足以防止 IDLE 停滞(因为输出长度/n,其中 n 是适度的整数仍然很大)。
1赞
Seaver
11/16/2023
#2
我一直在玩你的问题。打印截断的词典会满足您的需求吗?在这里,我应用了tutorialsport中的技术
import itertools
import pprint
# An arbitary, nested dictionary
nested_inner = {i: ['a', 'b', 'c'] for i in range(5)}
nested_mid = {chr(i): nested_inner for i in range(65, 70)}
nested_outer = {i: nested_mid for i in range(10000)}
# truncate the dictionary instead?
sample_data = dict(itertools.islice(nested_outer.items(), 500))
pprint.PrettyPrinter(indent=4, width=80, depth=3)
pprint.pprint(sample_data)
评论
0赞
SapereAude
11/17/2023
这看起来很有希望。对于我正在使用的词典,一些内部级别很大。例如,在您的示例中,我们可以将 range(5) 替换为 range(50000)。对于这种情况,这种方法是否有扩展或变体?
1赞
Kelly Bundy
11/17/2023
#3
您可以将数据格式化为字符串,将其拆分为行,并仅打印所需的行数:
for line in pprint.pformat(data).splitlines()[:42]:
print(line)
除了切片,您还可以打印所有行,并在看够后停止使用 Ctrl-C。
评论