列表生成式即List Comprehensions,是Python內置的很是簡單卻強大的能夠用來建立list的生成式。app
列表生成式能夠用一行語句代替循環生成一個list:spa
>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # 篩選出僅偶數的平方 >>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] # 使用兩層循環,生成全排列 >>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
for循環其實能夠同時使用兩個甚至多個變量,好比dict的items()能夠同時迭代key和value:code
>>> d = {'x': 'A', 'y': 'B', 'z': 'C'} >>> d {'x': 'A', 'y': 'B', 'z': 'C'} >>> for k, v in d.items(): ... print(k, '=', v) ... x = A y = B z = C
列表生成式也可使用兩個變量來生成list:blog
>>> d = {'x': 'A', 'y': 'B', 'z': 'C'} >>> [k + '=' + v for k, v in d.items()] ['x=A', 'y=B', 'z=C']
把list中全部的字符串變成小寫:字符串
>>> L = ['Hello', 'World', 'IBM', 'Apple'] >>> [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple']