【问题标题】:Short overview of contents of list of tuples元组列表内容的简短概述
【发布时间】:2012-12-06 21:02:37
【问题描述】:

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

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 解决方案,它只是说明一个观点的示例。

【问题讨论】:

  • 然后寻找带有连接的列表推导式?
  • 是什么让你认为这样的函数不是“Pythonic”? "Readability counts."
  • 谢谢,Johnsyweb。我实际上正在考虑引用“简单胜于复杂”。因为该功能会降低四到五个缩进级别。根据我有限的经验,如果在 Python 中缩进超过三个级别,那么 Guido 已经设计了一个更好的方法。
  • 确实如此,但减少行数并不能降低复杂性。平面比嵌套好,但这并不意味着嵌套不好。

标签: python debugging tuples


【解决方案1】:

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

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

【讨论】:

  • 很好,谢谢!这实际上返回了一个列表列表,但我可以使用它。再次感谢您向我介绍 lambda 函数。
【解决方案2】:

我会尝试继承 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 包装和对齐结构。它也只截断原始对象图中的字符串,而不是任何其他结构的结果字符串表示,但它完成了基本工作(没有输出太宽)。

【讨论】:

  • 谢谢,毫驼。正如我在 OP 中提到的,我正在寻找更简单的东西,而无需编写方法/函数。但这是重写方法的一个很好的例子,并且肯定会在后一种状态下派上用场。非常感谢!
  • @dotancohen 我的理由更多是“如果你想改变对象的格式,有一个地方为这个机制提供了钩子”。不幸的是,它不是内置的字符串格式,这使得这种方法不是很“轻量级”。所以这是一种选择,但我知道它可能不是你想要的。
猜你喜欢
  • 2020-08-28
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2011-11-06
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多