列表生成式即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']
?