在list comprehension中加入if条件判断:
>>> lines = [line.rstrip() for line in open('script2.py') if line[0] == 'p']
>>> lines
['print(sys.path)', 'print(x ** 32)']
这段代码相当于:
>>> res = []
>>> for line in open('script2.py'):
... if line[0] == 'p':
... res.append(line.rstrip())
...
>>> res
['print(sys.path)', 'print(x ** 32)']
在list comprehension中加入嵌套循环:
>>> [x+y for x in 'abc' for y in 'lmn']
['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']
这段代码相当于:
>>> res = []
>>> for x in 'abc':
... for y in 'lmn':
... res.append(x+y)
...
>>> res
['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']