# python – 理解列表理解

https://docs.python.org/2/tutorial/datastructures.html

``````>>>[(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)]
``````

>看起来列表理解从左到右进行评估.
>这种理解介绍了X和Y.
>然后按列表定义X和Y,并根据列表中的位置以及if条件进行评估.
>由于X被指定为第一个变量,就像嵌套for循环的外部一样,首先调用它并对Y的列表进行迭代.
> if条件使得理解只产生与X迭代通过Y列表不相似的对.

``````#      X           A                   B               C
a = [(x, y)   for x in [1,2,3]   for y in [3,1,4]   if x != y]
``````

``````__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
``````

``````#      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
``````

本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。