1.简介
列表生成式即List Comprehensions,是Python中用于创建list的生成式。
2.示例
[表达式 循环体 条件语句]
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 print [x * x for x in range(1, 11)] 5 print [x * x for x in range(1, 11) if x % 2 == 0] 6 print [m + n for m in 'ABC' for n in 'XYZ'] 7 8 d = {'x': 'A', 'y': 'B', 'z': 'C'} 9 print [k + '=' + v for k, v in d.items()] 10 11 L = ['Hello', 'World', 'IBM', 'Apple'] 12 print [s.lower() for s in L]
结果如下: