如何大声阅读Python列表推导? [英] How to read aloud Python List Comprehensions?
问题描述
我的问题是关于Python 列表理解的可读性.当我遇到具有复杂/嵌套列表理解的代码时,我发现我不得不重新阅读它们几次才能理解其意图.
My question is about Python List Comprehension readability. When I come across code with complex/nested list comprehensions, I find that I have to re-read them several times in order to understand the intent.
是否有一种直观的方法来朗读列表理解?似乎我应该从中间开始阅读",然后阅读 if 条件(如果有),然后阅读 表达式 最后.
Is there an intuitive way to read aloud list comprehensions? Seems like I should start "reading" from the middle, then read the if conditions (if any), and read the expression last.
这是我如何大声阅读下面的代码行,以便理解它:
Here's how I would read the follow line of code aloud, in order to understand it:
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
对于列表x中的每个元素和列表y中的每个元素,如果两个元素不相同,则创建元组列表."
"For each element in List x, and each element in List y, if the two elements are not the same, create a list of tuples."
我正在苦苦挣扎的两个例子: 您将如何大声阅读以下列表理解?
Two examples that I am struggling with: How would you read the following List Comprehensions aloud?
-
来自堆栈溢出的另一个问题:
[x for b in a for x in b]
Python文档具有以下示例:
[[row[i] for row in matrix] for i in range(4)]
Python docs has this example:
[[row[i] for row in matrix] for i in range(4)]
任何对大声朗读列表理解方式的建议或指针,都可以使意图变得更加清晰.
Any suggestions or pointers for ways to read aloud list comprehensions such that the intention becomes clearer is much appreciated.
推荐答案
我通常在脑海中将其展开为一个生成循环,例如
I usually unfold it in my mind into a generating loop, so for example
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
是生成器的列表理解
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
yield (x, y)
示例1
[x for b in a for x in b]
是对
Example #1
[x for b in a for x in b]
is the comprehension for
for b in a:
for x in b:
yield x
a = [[1,2,3],[4,5,6]]
的示例结果:[1, 2, 3, 4, 5, 6]
[[row[i] for row in matrix] for i in range(4)]
(请注意,内部表达式是另一种理解!):
[[row[i] for row in matrix] for i in range(4)]
(note the inner expression is another comprehension!):
for i in range(4):
yield [row[i] for row in matrix]
已展开
for i in range(4):
l = []
for row in matrix:
l.append(row[i])
yield l
这篇关于如何大声阅读Python列表推导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!