python教程—python列表理解双for-Python实用宝典

# python教程—python列表理解双for

```vec = [[1,2,3], [4,5,6], [7,8,9]]
print [num for elem in vec for num in elem]      <----- this

>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

python如何解释这个?

```[x for x in collection]
```

• A是将出现在结果列表中的项
• B是集合C中的每一项
• C是集合本身。

```[x.lower() for x in words]
```

```[x for y in collection for x in y] # [A for B in C for D in E]
```

• A是将出现在结果列表中的项
• B是集合C中的每一项
• C是集合本身
• D是集合E中的每一项(在本例中，也是A)
• E是另一个集合(本例中为B)

```for y in collection:     #      for B in C:
for x in y:          #          for D in E: (in this case: for A in B)
```

```[z for b in a for c in b for d in c ... for z in y]
```

```for b in a:
for c in b:
for d in c:
...
for z in y:
# have z
```

```[line for line in file if not line.startswith('#')]
```

```for line in file:
if not line.startswith('#'):
# have line
```

```>>> z = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
>>> [x for y in z if sum(y)>10 for x in y if x < 10]
[5, 6, 7, 8, 9]
```

```>>> for y in z:
if sum(y)>10:
for x in y:
if x < 10:
print x

5
6
7
8
9
```

​Python实用宝典 (pythondict.com)