DAY 9
1

List Comprehesion

``````squares = []
for x in range(10):
squares.append(x**2)

# Output
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
``````

``````squares = list(map(lambda x: x**2, range(10)))
``````

``````squares = [x**2 for x in range(10)]
``````

List Comprehesion的語法

`[expression for item in iterable]`其中：

• expression為表達式
• iterable為可迭代的物件
• item為迭代中的變數

條件式

`[expression for item in iterable if condition]`其中：

• expression為表達式
• iterable為可迭代的物件
• item為迭代中的變數
• condition為條件式

``````odd_squares = [x**2 for x in range(10) if x%2 != 0]

# Output
odd_squares
[1, 9, 25, 49, 81]
``````

巢狀迴圈

`[expression for item in iterable for item2 iterable2 ...]`其中：

• expression為表達式
• iterable為可迭代的物件
• item為迭代中的變數

``````table = [x*y for x in range(10)[1:] for y in range(10)[1:]]

# Output
table
[1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 6, 9, 12, 15, 18, 21, 24, 27, 4, 8, 12, 16, 20, 24, 28, 32, 36, 5, 10, 15, 20, 25, 30, 35, 40, 45, 6, 12, 18, 24, 30, 36, 42, 48, 54, 7, 14, 21, 28, 35, 42, 49, 56, 63, 8, 16, 24, 32, 40, 48, 56, 64, 72, 9, 18, 27, 36, 45, 54, 63, 72, 81]
``````

``````table = [[x*y for x in range(10)[1:]] for y in range(10)[1:]]

# Output
table
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15, 18, 21, 24, 27], [4, 8, 12, 16, 20, 24, 28, 32, 36], [5, 10, 15, 20, 25, 30, 35, 40, 45], [6, 12, 18, 24, 30, 36, 42, 48, 54], [7, 14, 21, 28, 35, 42, 49, 56, 63], [8, 16, 24, 32, 40, 48, 56, 64, 72], [9, 18, 27, 36, 45, 54, 63, 72, 81]]
``````

其他

`[expression if-else clause for item in iterable condition/iterable]`其中：

• expression為表達式
• if-else clause為if-else子句
• iterable為可迭代的物件
• item為迭代中的變數
• condition為條件式

Reference

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
Python Basics:List Comprehesions
https://towardsdatascience.com/python-basics-list-comprehensions-631278f22c40

30天學會Python30