对列表理解而言,复杂程度有多复杂?

时间:2015-04-18 02:37:36

标签: python list-comprehension

列表推导是Python中一个非常强大的工具,但有时候我发现自己在其中放了很多东西。在什么时候写一个函数而不是把它放在列表理解中更好?

例如:

>>> m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [''.join([[str(x) for x in i] for i in m][j]) for j in [0, 1, 2]]
['123', '456', '789']

3 个答案:

答案 0 :(得分:3)

您的代码可以重写为更易读和简洁:

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print([''.join(map(str, sub)) for sub in m])

['123', '456', '789']

通常我会远离您发布的代码。它不是最易读的代码,但这是一个意见,基本上是你可能会得到Guido的唯一答案。

python的禅应该是指向你的代码是否是pythonic代码的一个很好的例子的指针。

In [49]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

答案 1 :(得分:1)

这是风格和个人偏好的问题。当列表理解变得笨拙时,最好将其转换为函数。良好的Python风格强调代码可读性。

答案 2 :(得分:0)

没有严格的指导原则 - 您必须根据具体情况评估代码。要记住的最重要的事情是代码的读取频率高于编写代码 - 因此,即使某些东西更有效(或更紧凑),它也不一定更好。在您的特定情况下,阅读理解是相当困难的,我建议重写它(如Padraic所建议)或将其放入函数中。此外,您可以使用空格来更有效地组织代码。最后,如果您正在设置使其成为列表理解,您可以编写辅助函数,您可以在列表理解中调用 - 这将实现类似(但更糟糕的是 - 尽可能使用标准库)结果作为Padraic&# 39;解决方案。