禁用打印输出中的排序机制 [英] Disabling sorting mechanism in pprint output
本文介绍了禁用打印输出中的排序机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
您可以猴子补丁 pprint模块。
import pprint
pprint.pprint({abc:1,def:2,ghi:3} )
pprint._sorted = lambda x:x
pprint.pprint({abc:1,def:2,ghi:3})
由于第二个输出是必要的随机排序,您的输出可能与我的不同:
{'abc':1,'def':2,'ghi':3}
{'abc':1,'ghi':3,'def' :2}
另一个更复杂的版本,但更容易使用:
import pprint
import contextlib
@ contextlib.contextmanager
def pprint_nosort():
orig,pprint._sorted = pprint。 _sorted,lambda x:x
try:
yield
finally:
pprint._sorted = orig
#对于不想排序的时候输出
与pprint_nosort():
pprint.pprint({abc:1,def:2,ghi:3})
#你想要排序输出
pprint.pprint({abc:1,def:2,ghi:3})
I have big dictionary which I`m printing for viewing with prettyprint, but how I can keep formatting but kill sorting mechanism in pprint?
解决方案
You can monkey patch the pprint module.
import pprint
pprint.pprint({"abc":1,"def":2,"ghi":3})
pprint._sorted = lambda x:x
pprint.pprint({"abc":1,"def":2,"ghi":3})
Since the 2nd output is essentiallly randomly sorted, your output may be different from mine:
{'abc': 1, 'def': 2, 'ghi': 3}
{'abc': 1, 'ghi': 3, 'def': 2}
Another version that is more complex, but easier to use:
import pprint
import contextlib
@contextlib.contextmanager
def pprint_nosort():
orig,pprint._sorted = pprint._sorted, lambda x:x
try:
yield
finally:
pprint._sorted = orig
# For times when you don't want sorted output
with pprint_nosort():
pprint.pprint({"abc":1,"def":2,"ghi":3})
# For times when you do want sorted output
pprint.pprint({"abc":1,"def":2,"ghi":3})
这篇关于禁用打印输出中的排序机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文