【发布时间】: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 已经设计了一个更好的方法。
-
确实如此,但减少行数并不能降低复杂性。平面比嵌套好,但这并不意味着嵌套不好。