Python能夠用一行代碼作不少事情,其中包括生成一個符合特定規則的列表,以下所示:函數
下面的代碼用到了:**運算符,for in關鍵詞,range函數,if not關鍵詞spa
>>> aListOf2 = [2**x for x in range(10)] >>> aListOf2 [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] >>> aListOf2 = [2**x for x in range(10) if x > 5] >>> aListOf2 [64, 128, 256, 512] >>> aListOf2 = [2**x for x in range(10) if not x <= 4] >>> aListOf2 [32, 64, 128, 256, 512] >>>