列表元组内容简介

2024-04-29 15:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设一个元组列表,包含任意长度的内容:

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解,它只是一个例子来说明一个观点。你知道吗


Tags: andthetoyou内容列表thatis
2条回答

我会尝试子类化^{}。浏览一下源代码,您要覆盖的方法似乎是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包装和排列结构。它还只截断原始对象图中的字符串,而不是任何其他结构的结果字符串表示形式,但它完成了基本工作(没有太宽的输出)。你知道吗

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

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

相关问题 更多 >