list comprehension 后面可以有多个for loops,每个for后面可以有if
[(x, y, x * y)for x in(0,1,2,3)for y in(0,1,2,3)if x < y]
等同于:
for x in (0,1,2,3): for y in (0,1,2,3): if x < y: print (x, y, x*y)
It also supports both “if" statements and referencing the outer iterator from the inner one, like so:
>>> seq = ['abc', 'def', 'g', 'hi'] ... [y for x in seq if len(seq) > 1 for y in x if y != 'e'] ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i']
等同于:
>>> result = [] ... for x in seq: ... if len(seq) > 1: ... for y in x: ... if y != 'e': ... result.append(y) ... result ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i']
(说明一下,第一个for loop里面的if从句是多余的,len(seq)一直不变。
参考:http://stackoverflow.com/questions/7847624/list-comprehension-for-loops-python
http://rhodesmill.org/brandon/2009/nested-comprehensions/
http://www.python-course.eu/list_comprehension.php