1. 程式人生 > >少說話多寫程式碼之Python學習033——迴圈語句03(列表導式)

少說話多寫程式碼之Python學習033——迴圈語句03(列表導式)

列表導式是利用列表建立新的列表,比如,下面建立一個列表

a=[x*x for x in range(10)]
print(a)

輸出

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

建立列表過程中也可以增加條件,比如,只要能被2整除的數。

b=[x*x for x in range(10) if x%2 == 0]
print(b)

輸出

[0, 4, 16, 36, 64]

還可以使用多個for語句還建立這樣的列表,

c=[(x,y) for x in range(3) for y in range(3)]
print(c)

輸出

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

再看看,用兩層迴圈來建立列表,

result = []
for x in range(3):
    for y in range(3):
        result.append((x,y))
        print(result)

輸出

[(0, 0)]
[(0, 0), (0, 1)]
[(0, 0), (0, 1), (0, 2)]
[(0, 0), (0, 1), (0, 2), (1, 0)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

工程檔案下載:https://download.csdn.net/download/yysyangyangyangshan/10752006