python基礎之列表生成式
阿新 • • 發佈:2018-12-05
例1:
>>> List=[x for x in range(10)]
>>> List
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
等價於:
>>> List=[]
>>> for x in range(10):
List.append(x)
>>> List
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
例2:
>>> List=[x+3 for x in range(10)] >>> List [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> a=[1,2,3,4,5] >>> List=[x*2 for x in a] >>> List [2, 4, 6, 8, 10]
例3:兩個for迴圈
>>> List=[x for x in range(3) for x in range(5)]
>>> List
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
等價於:
>>> List=[] >>> for x in range(3): for x in range(5): List.append(x) >>> List [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
例4:
>>> List=[(x,y) for x in range(3) for y in range(4)]
>>> List
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
等價於:
>>> List=[] >>> for x in range(3): for y in range(4): List.append((x,y)) >>> List [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
例5:for 迴圈後面跟if條件語句: 用if 語句判斷,當if後面的語句值為真時,將對應的元素放入列表
>>> List=[x for x in range(3) for x in range(8) if x%2==0]
>>> List
[0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6]