2

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

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”的方式。在那儿?

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

4

2 回答 2

3

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

N = 10
map(lambda t: map(lambda s: s[:N], t), quotes)
于 2012-12-06T21:14:02.253 回答
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

于 2012-12-06T21:20:41.103 回答