理解列表理解 [英] Comprehending List Comprehensions
问题描述
最近我被介绍列出理解,但是,我不确定我是否完全理解它们.
I have been recently introduced to list comprehensions, however, I am not certain I understand them completely.
因此,我通过文档和Google进行了快速搜索. 我在数据结构上找到了docs部分.
So, I did a quick search through the docs and google. I found the docs section over data structures.
https://docs.python.org/2/tutorial/datastructures.html
虽然让我对它们的工作方式有所了解,但让我感到陌生,但我想对它们的运行方式有更成熟的了解.
While that gives me an idea with how they work, call me strange, I want to have a more mature understanding of how they operate.
这是文档中的一个示例:
Here is an example from the docs:
>>>[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
如果我错了,请纠正我,但这是我了解列表评估方式的方式.
Correct me if I am wrong, but this is how I understand how the list is evaluating.
- 列表理解似乎是从左到右评估的.
- 这种理解引入了X和Y.
- 然后通过列表定义X和Y,并根据列表中的位置以及if条件进行评估.
- 由于将X分配为第一个变量,就像嵌套的for循环的外部一样,因此将其首先调用并针对Y的列表进行迭代.
- 如果条件满足,则理解仅会产生与X遍历Y的列表不相似的对.
如果我的理解不正确,请纠正我. 我欢迎更复杂的理解实例.
Please correct me if my understanding is incorrect. I welcome more complex examples for comprehensions.
推荐答案
嵌套列表推导没有任何魔术.我认为您还没有看到它们的简单性!
There's nothing magic about nested list comprehensions. I think you're simply not seeing their simplicity yet!
此:
# X A B C
a = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
仅仅是以下方面的语法糖:
is simply syntactic sugar for:
__tmp = []
for x in [1,2,3]: # A
for y in [3,1,4]: # B
if x != y: # C
__tmp.append((x, y)) # X
a = __tmp
因此,您将for ... in ...
零件重新组装成嵌套的for
循环.然后,您将if
放入相应的for
循环中;最后,使用第一部分(在本例中为(x, y)
),然后嵌套在嵌套的for
结构的最深部分.
So you take the for ... in ...
parts and re-assemble them as nested for
loops. You then take the if
s and nest it in the corresponding for
loop; finally, you take the first part ((x, y)
in this case) and you nest at the deepest part of the nested for
structure.
当if
出现在列表理解中的多个阶段"时,这也可以正常工作,例如:
This works out fine also when if
s appear at multiple "stages" in a list comprehension, for example:
# X A B C D
a = [(x, y) for x in [1,2,3] if x >= 2 for y in [3,1,4] if x != y]
将(反义词)翻译为:
__tmp = []
for x in [1,2,3]: # A
if x >= 2: # B
for y in [3,1,4]: # C
if x != y: # D
__tmp.append((x, y)) # X
a = __tmp
再说一遍……这与散布在各个部分之间的冒号的理解完全相同,而内部部分则位于前面. A B C D ...
部分的顺序始终相同,并且从未更改.只是X
部分从后向前移动.
So again... it's just exactly the same as the comprehension with colons interspersed between the parts, and the inner part brought right in the front. The order of the A B C D ...
part is always the same and never changed; it's only the X
part that's moved from the back to the front.
这篇关于理解列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!