列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
最常见的例子:
生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)):>>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
进阶:要生成[1x1, 2x2, 3x3, ..., 10x10]
怎么做?
>>>L = [x * x for x in range(1, 11)] >>>L[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
进阶:for循环中加if
>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]
进阶:两个for循环生成list
>>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
举例:
把一个list中所有的字符串变成小写:>>> L = ['Hello', 'World', 'IBM', 'Apple'] >>> [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple']