Python漂亮打印字典的列表,缩写长列表 [英] Python pretty print dictionary of lists, abbreviate long lists

查看:264
本文介绍了Python漂亮打印字典的列表,缩写长列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表的列表,列表很长。如何以列表中只有几个元素显示的方式打印?显然,我可以编写一个自定义函数,但是有没有内置的方法或库可以实现这一点?例如,当打印大数据帧时, pandas 可以很简单地打印出来。



此示例更好地说明了我的意思:

  obj = { 'key_1':['EG8XYD9FVN',
'S2WARDCVAO',
'J00YCU55DP',
'R07BUIF2F7',
'VGPS1JD0UM',
'WL3TWSDP8E',
'LD8QY7DMJ3',
'J36U3Z9KOQ',
'KU2FUGYB2U​​',
'JF3RQ315BY'],
'key_2':['162LO154PM',
' 3ROAV881V2',
'I4T79LP18J',
'WBD36EM6QL',
'DEIODVQU46',
'KWSJA5WDKQ',
'WX9SVRFO0G',
'6UN63WU64G' ,
'3Z89U7XM60',
'167CYON6YN']}

期望的输出:如下所示:

  {'key_1':
['EG8XYD9FVN','S2WARDCVAO','... '],
'key_2':
['162LO154PM','3ROAV881V2','...']
}


解决方案

如果不是漂亮的打印, reprlib 模块将是要走的路:安全对于深度嵌套和递归/自引用的数据结构的优雅和可定制的处理是它所做的。



然而,结果是将 reprlib pprint 模块不是微不足道,至少我不能打破(某些)漂亮的打印方面的干净方式。



所以,这里是一个解决方案,只是将 PrettyPrinter 裁剪/根据需要缩写列表:

  from pprint import PrettyPrinter 


obj = {
'key_1':[
'EG8XYD9FVN','S2WA RDCVAO','J00YCU55DP','R07BUIF2F7','VGPS1JD0UM',
'WL3TWSDP8E','LD8QY7DMJ3','J36U3Z9KOQ','KU2FUGYB2U​​','JF3RQ315BY',
] key_2':[
'162LO154PM','3ROAV881V2','I4T79LP18J','WBD36EM6QL','DEIODVQU46',
'KWSJA5WDKQ','WX9SVRFO0G','6UN63WU64G','3Z89U7XM60','167CYON6YN ',
],
#测试用例,以确保我们没有中断处理递归结构
'key_3':[
'162LO154PM','3ROAV881V2',[1 ,2,['a','b','c'],3,4,5,6,7],
'KWSJA5WDKQ','WX9SVRFO0G','6UN63WU64G','3Z89U7XM60','167CYON6YN ',
]
}


class CroppingPrettyPrinter(PrettyPrinter):

def __init __(self,* args,** kwargs) :
self.maxlist = kwargs.pop('maxlist',6)
返回PrettyPrinter .__ init __(self,* args,** kwargs)

def _format(self,obj,stream,indent,allowance,context,level):
if isinstance(obj,list):
#如果对象是列表,则根据自己裁剪一个副本。 maxlist
#并附加省略号
如果len(obj)> self.maxlist:
cropped_obj = obj [:self.maxlist] + ['...']
return PrettyPrinter._format(
self,cropped_obj,stream,indent,
允许,上下文,级别)

#让原始实现处理其他任何东西
#注意:没有使用super(),因为PrettyPrinter是一个旧式的类
返回PrettyPrinter。 _format(
self,obj,stream,indent,allowance,context,level)


p = CroppingPrettyPrinter(maxlist = 3)
p.pprint(obj)






输出与 maxlist = 3

  {'key_1':['EG8XYD9FVN','S2WARDCVAO','J00YCU55DP' ''',
'key_2':['162LO154PM',
'3ROAV881V2',
[1,2,['a','b','c' ,'...'],
'...']}

输出与米axlist = 5 (触发将列表分开排列):

  {'key_1' 'EG8XYD9FVN',
'S2WARDCVAO',
'J00YCU55DP',
'R07BUIF2F7',
'VGPS1JD0UM',
'...'],
'key_2':['162LO154PM',
'3ROAV881V2',
'I4T79LP18J',
'WBD36EM6QL',
'DEIODVQU46',
'... '],
'key_3':['162LO154PM',
'3ROAV881V2',
[1,2,['a','b','c'],3,4 ,'...'],
'KWSJA5WDKQ',
'WX9SVRFO0G',
'...']}






注意:




  • 将创建列表的副本。根据数据结构的大小,这在内存使用方面可能非常昂贵。

  • 这仅涉及列表的特殊情况。等级行为必须针对dict,tuples,sets,frozensets ...实现,这个类是一般使用的。


I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function for that but is there any built-in way or library that can achieve this? For example when printing large data frames, pandas prints it nicely in a short way.

This example better illustrates what I mean:

obj = {'key_1': ['EG8XYD9FVN',
  'S2WARDCVAO',
  'J00YCU55DP',
  'R07BUIF2F7',
  'VGPS1JD0UM',
  'WL3TWSDP8E',
  'LD8QY7DMJ3',
  'J36U3Z9KOQ',
  'KU2FUGYB2U',
  'JF3RQ315BY'],
 'key_2': ['162LO154PM',
  '3ROAV881V2',
  'I4T79LP18J',
  'WBD36EM6QL',
  'DEIODVQU46',
  'KWSJA5WDKQ',
  'WX9SVRFO0G',
  '6UN63WU64G',
  '3Z89U7XM60',
  '167CYON6YN']}

Desired output: something like this:

{'key_1':
    ['EG8XYD9FVN', 'S2WARDCVAO', '...'],
 'key_2':
    ['162LO154PM', '3ROAV881V2', '...']
}

解决方案

If it weren't for the pretty printing, the reprlib module would be the way to go: Safe, elegant and customizable handling of deeply nested and recursive / self-referencing data structures is what it has been made for.

However, it turns out combining the reprlib and pprint modules isn't trivial, at least I couldn't come up with a clean way without breaking (some) of the pretty printing aspects.

So instead, here's a solution that just subclasses PrettyPrinter to crop / abbreviate lists as necessary:

from pprint import PrettyPrinter


obj = {
    'key_1': [
        'EG8XYD9FVN', 'S2WARDCVAO', 'J00YCU55DP', 'R07BUIF2F7', 'VGPS1JD0UM',
        'WL3TWSDP8E', 'LD8QY7DMJ3', 'J36U3Z9KOQ', 'KU2FUGYB2U', 'JF3RQ315BY',
    ],
    'key_2': [
        '162LO154PM', '3ROAV881V2', 'I4T79LP18J', 'WBD36EM6QL', 'DEIODVQU46',
        'KWSJA5WDKQ', 'WX9SVRFO0G', '6UN63WU64G', '3Z89U7XM60', '167CYON6YN',
    ],
    # Test case to make sure we didn't break handling of recursive structures
    'key_3': [
        '162LO154PM', '3ROAV881V2', [1, 2, ['a', 'b', 'c'], 3, 4, 5, 6, 7],
        'KWSJA5WDKQ', 'WX9SVRFO0G', '6UN63WU64G', '3Z89U7XM60', '167CYON6YN',
    ]
}


class CroppingPrettyPrinter(PrettyPrinter):

    def __init__(self, *args, **kwargs):
        self.maxlist = kwargs.pop('maxlist', 6)
        return PrettyPrinter.__init__(self, *args, **kwargs)

    def _format(self, obj, stream, indent, allowance, context, level):
        if isinstance(obj, list):
            # If object is a list, crop a copy of it according to self.maxlist
            # and append an ellipsis
            if len(obj) > self.maxlist:
                cropped_obj = obj[:self.maxlist] + ['...']
                return PrettyPrinter._format(
                    self, cropped_obj, stream, indent,
                    allowance, context, level)

        # Let the original implementation handle anything else
        # Note: No use of super() because PrettyPrinter is an old-style class
        return PrettyPrinter._format(
            self, obj, stream, indent, allowance, context, level)


p = CroppingPrettyPrinter(maxlist=3)
p.pprint(obj)


Output with maxlist=3:

{'key_1': ['EG8XYD9FVN', 'S2WARDCVAO', 'J00YCU55DP', '...'],
 'key_2': ['162LO154PM',
           '3ROAV881V2',
           [1, 2, ['a', 'b', 'c'], '...'],
           '...']}

Output with maxlist=5 (triggers splitting the lists on separate lines):

{'key_1': ['EG8XYD9FVN',
           'S2WARDCVAO',
           'J00YCU55DP',
           'R07BUIF2F7',
           'VGPS1JD0UM',
           '...'],
 'key_2': ['162LO154PM',
           '3ROAV881V2',
           'I4T79LP18J',
           'WBD36EM6QL',
           'DEIODVQU46',
           '...'],
 'key_3': ['162LO154PM',
           '3ROAV881V2',
           [1, 2, ['a', 'b', 'c'], 3, 4, '...'],
           'KWSJA5WDKQ',
           'WX9SVRFO0G',
           '...']}


Notes:

  • This will create copies of lists. Depending on the size of the data structures, this can be very expensive in terms of memory use.
  • This only deals with the special case of lists. Equivalent behavior would have to be implemented for dicts, tuples, sets, frozensets, ... for this class to be of general use.

这篇关于Python漂亮打印字典的列表,缩写长列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆