简要概述元组列表的内容

时间:2012-12-06 21:02:37

标签: python debugging tuples

假设一个元组列表,其内容为任意长度:

quotes = [('Shakespeare', 'Piccard', 'Allen'),
          ("To be, or not to be", "Earl Grey, 60 degrees", "I feel that life is divided into the horrible and the miserable. That's the two categories. The horrible are like, I don't know, terminal cases, you know, and blind people, crippled. I don't know how they get through life. It's amazing to me. And the miserable is everyone else. So you should be thankful that you're miserable, because that's very lucky, to be miserable."),
          ('beer', 'tea', 'vodka')
         ]

出于调试目的,我想输出列表的内容:

print str(quotes)

但是,我只想要任何元组值的前N个字符,如果它在第三个引用中很长,我不需要整个内容。 我知道我可以编写一个函数迭代列表,然后迭代每个元组并切片前N个字符,但是Python我怀疑有更简单,更短,更“Pythonic”的方式。 / strong>有吗?

我不是在寻找当前示例的XY解决方案,它只是一个例子来说明这一点。

2 个答案:

答案 0 :(得分:3)

不确定这是否足够pythonic,但仍然:

N = 10
map(lambda t: map(lambda s: s[:N], t), quotes)

答案 1 :(得分:1)

我会尝试继承PrettyPrinter。浏览源代码,您想要覆盖的方法似乎是format(self, object, context, maxlevels, level)

import pprint

class TruncatingPrettyPrinter(pprint.PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, basestring):
            object = object[:72]+"..." # shorten strings to under 80 chars

        return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)

TruncatingPrettyPrinter().pprint(quotes)

print str(quotes)完全相同 ,因为pprint包装和对齐结构。它也只截断原始对象图中的字符串,而不是任何其他结构的结果字符串表示,但它完成了基本工作(没有输出太宽)。