Python 对于列表理解来说,有多复杂太复杂?

Python 对于列表理解来说,有多复杂太复杂?,python,list-comprehension,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'] 您的代码可以重写为更具可读性和简洁性: m = [[1, 2,

列表理解在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']

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

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

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

['123', '456', '789']
一般来说,我会远离您发布的代码。这不是最可读的代码,但这是一种观点,基本上是您可能得到的唯一答案

python的zen应该是一个指针,指示您的代码是否是python代码的好例子

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!

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

没有硬性的指导原则-您必须逐个评估代码。要记住的最重要的一点是,代码的读取频率比编写频率高——因此,即使某些东西更高效(或更紧凑),也不一定更好。在您的特定情况下,阅读和理解代码是相当困难的,我建议重写它(如Padraic所建议的)或将其放入函数中。此外,还可以使用空格更有效地组织代码。最后,如果你想让它成为一个列表理解,你可以编写一个帮助函数,你可以在列表理解中调用它——这将获得与Padraic解决方案类似的结果(但更糟糕的是,如果可能的话使用标准库)。

当它变得迟钝、不可读时。。。。