[Python] List Comprehensions

List Comprehensions

List Comprehension [with Condition]

[e for e in array [if e …]]

2-Dimensional List Comprehension

 mat = [1 * n] * m ⇒ [n, n, …, n]
 mat = [[1] * n]] * m ⇒ mat[i] is mat[j] for 0 <= i, j < n and i != j (caused by soft copy
mat = [[1 * n] for _ in range(m)]

因為 list 的 multiplication 是 shallow copy

mat = [[1] * n]] * m 
# mat → [   [1, 1, ..., 1],    [1, 1, ..., 1], ...,    [1, 1, ..., 1]]

mat[0].append(2)     
# mat → [[1, 1, ..., 1, 2], [1, 1, ..., 1, 2], ..., [1, 1, ..., 1, 2]]

Nest List Comprehensions

[row[y][x] for row in mat for x in range(len(row))]

和 For Loop 的差別

使用 For Loop

a = [1, 2, 3, 4, 5]

a[0] -= 1
for i in range(1, len(a)):
  a[i] -= a[i - 1]

--

Result: 
a: [0, 2, 1, 3, 2]

使用 List Comprehensions

a = [1, 2, 3, 4, 5]

a = [(a[i] - (1 if i == 0 else a[i - 1])) for i in range(len(a))]
# 整個列表構建完成才賦值給 a


--

Result: 
a: [0, 1, 1, 1, 1]

Last Updated on 2023/09/12 by A1go

目錄
Bitnami