简单的例子
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
复杂些的例子——找出首字母相同的男孩和女孩
>>> girls = ['alice','bernice','clarice']
>>> boys = ['chris','arnold','bob']
>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
效率更高的实现
>>> girls = ['alice','bernice','clarice']
>>> boys = ['chris','arnold','bob']
>>> letterGirls = {}
>>> for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
>>> print [b + '+' + g for b in boys for g in letterGirls[b[0]]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
>>> letterGirls
{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
摘自《Python基础教程》