DAY 6
0
AI & Data

# Python 基礎語法教學 Part 4

## 情境題

``````arr1 = []

for i in range(10):
arr1.append(i)

print(arr1)
``````

## 使用List Comprehension

``````# in-place construction
arr1 = [i for i in range(10)]

print(arr1)
``````

## 變化型List Comprehension

``````# in-place construction
arr1 = [i for i in range(10)]

# you can use if to filter the elements
arr2 = [x for x in arr1 if x % 2 == 0]

# you can use as many conditions as you want!
arr3 = [x for x in arr1 if x >= 3 and x % 2]

# use nested for loops to make everyone dizzy XD
arr4 = [(x, y) for x in range(3) for y in range(4)]

print(arr1)
print(arr2)
print(arr3)
print(arr4)
``````

`arr2`要放什麼? 放`x`
`x`怎麼來，從後面的for來。
for從啥提取元素? 從`arr1`

.
.
.

## List Comprehension的效率

``````import time

arr1 = []
s = time.time()
for i in range(int(1e+6)):
arr1.append(i)
print('took {} secs'.format(round(time.time() - s, 3)))

s = time.time()
arr2 = [i for i in range(int(1e+6))]
print('took {} secs'.format(round(time.time() - s, 3)))
``````

``````took 0.148 secs
took 0.07 secs
``````

## 引入模組

``````# standard import
import time

# import and give alias
import random as rd

# precise imoprt
from pathlib import Path

# useless statement
from datetime import *
``````

1. 使用`import`關鍵字引入模組
2. 可引入模組後，用`as`幫他取暱稱，這樣就可以不用打又臭又長的套件名稱XD
3. 可使用`import ... from ...`的語法，從某套件中拿出特定的功能
4. 最後一個方法感覺很糟，會汙染全域，建議不要使用XD

## List Comprehension背後的原理

``````# what if we don't assign comprehension to list?
comp = (i for i in range(10))
print(comp)
print(type(comp))

arr1 = list(comp)
arr2 = list(comp)
arr3 = [comp]
print(arr1)
print(arr2)
print(arr3)
``````

## 小練習

``````1 <---> 2
3 <---> 4
5 <---> 6
7 <---> 8
9 <---> 10
11 <---> 12
13 <---> 14
15 <---> 16
17 <---> 18
19 <---> 20
``````

### 1 則留言

0
DeepLearner
iT邦新手 5 級 ‧ 2020-05-20 22:08:56