Created
March 10, 2013 13:44
-
-
Save fkztw/5128627 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
今日投影片 j.mp/mosky-python | |
最新版投影片 j.mp/mosky-py | |
print 'Print', 'multiple' # Print 和 multiple 中間會有空白 | |
# 在 python2 裏面拿不掉 | |
# 可以用 sys 裏面的 write 代替 就沒有空白 | |
print #印一個新行 | |
print() #python3 | |
print('End with a space.', end='') # 會把最後因為逗號出現的空白去掉 | |
print('A', 'B', 'C', sep=',') # sep 預設是一個空白 | |
sequence comparison | |
python 裏面沒有字元 只有長度為1的字串 | |
所以 'A' > 65 是 True | |
通常不會拿 字串 和 整數 做比較 只是要讓大家比較了解 | |
在 python3 裏面用 seq 跟不是 seq 的型態比較會出現 type error | |
if-else 補充 (類似 Ternary 的用法) | |
[exp. if conditon true] if [condition] else [exp. if condition false] | |
try | |
#python2 | |
try: | |
... | |
except LookupError, e: | |
... | |
except (IndexError, KeyError), e: | |
... | |
else: | |
... | |
finally: | |
... | |
#python3 | |
try: | |
... | |
except LookupError as e: | |
... | |
except (IndexError, KeyError) as e: | |
... | |
else: | |
... | |
finally: | |
... | |
避免使用 Exception (所有 exceptions 的父類別, 會抓到所有的例外) | |
除非是在頂層, 如果 except 後面不寫東西, 也是代表抓所有的例外 | |
try 裏面的 code 要儘量減少, 儘量把要執行的 code 放在 else | |
finally 用來寫意外發生的時候要如何善後的code | |
raise KeyError('xxxxx') | |
def | |
定義一個function | |
如果沒寫回傳值的話 會回傳None | |
unpack 用法 | |
f(1, 2) == f(*(1, 2)) | |
f(y=2, x=1) == f(**{'y':2, 'x':1}) | |
def f(*args): # *args 代表接受任意長度的參數 | |
return args # 回傳一個 tuple | |
def f(**kargs): # **kargs 可以接受 keyword argument | |
return kargs # 回傳一個 key 和 value 對應的 dictionary | |
def f(x, *args): | |
return x, args | |
def f(x, **kargs): | |
return x, kargs | |
def f(*args, y): # Syntax Error, 特定的argument要放在 *args 前面 | |
return args | |
def f(*args, **kargs): # 接收所有的參數 | |
return args, kargs # 可以透過這樣的寫法 | |
# 將所有參數原封不動傳給另外一個function | |
# 最好是 hack 別人的 library 或是 | |
# 要修正自己的 function 時再用 | |
# def statement in python3 | |
def f(*args, k): # python3 比較彈性 這樣寫不會噴 syntax error | |
return k, args # 但 k 只能用 keyword argument 指定 | |
# 因為所有 position 指定的方式都會被 *args 吃掉 | |
# python functions are first-class functions | |
# you can pass functions as arguments and assign functions to variables | |
# like function pointer in c | |
A trap of the default value | |
參見 ex_defval_trap.py | |
# list 是在 function define 的時候就建立了, 不是在 function 被 called 的時候 | |
# 而 list = [] 這個方式並不會把原本就存在的 list 清空 | |
# 所以避免用 Mutable types 來當 default value | |
# 如果要用的話 可以使用類似下面這種方式 | |
def (items=None): | |
if items is None: | |
items = [] | |
items.append(1) | |
return items | |
# 這樣就可以每次把list清空 | |
x, y = [1, 2] | |
x, y = (1, 2) | |
# x == 1 , y == 2 | |
可用 y, x = x, y 直接做 swap | |
file object | |
read | |
f = open('input.txt') | |
print f.read() | |
f.seek(0) | |
for line in f: | |
print line, | |
f.close() | |
write | |
f = open('output.txt', 'w') | |
f.write('a line.\n') #要記得加換行符 | |
f.close() | |
csv module | |
import csv | |
with open('ex_csv.csv') as f: | |
for row in csv.reader(f): | |
print row | |
Documentation ( docs.python.org/2/ or docs.python.org/3/ ) | |
help($name) | |
dir($name) | |
'\n'.join(dir($name)) | |
pydoc $name | |
Your Documentation | |
可以自己寫 pydoc 說明自己寫的東西 | |
可以用 python 來寫測試其他語言的工具 | |
Data model 有許多 special method (__xxx__) 的詳細說明 | |
Scope | |
function scope -> scopes are decided by functions. | |
The LEGB Rule (python 變數查找的規則) | |
變數查找順序 local -> enclosed -> global -> built-in | |
clime.mosky.tw -> 自動將 python code 轉為 command line 介面的 script | |
locals()[sys.argv[1]]() | |
Module and Package | |
import module #module.py | |
資料夾底下有 __init__.py 的話 就是 python 的 package | |
import package # __init__.py , package 指的是該資料夾的名字 | |
import package.module #package/module.py | |
import .module # package/module.py | |
$ python -m package.module | |
不要把自訂的 module 的名字取的跟 built-in module 的名字一樣 | |
typing | |
python is not static typing, is dynamic typing | |
Dynamic typing | |
check types in run time | |
a variable just points to an object | |
一個變數的 reference counter 歸零後, 就會被GC回收 | |
Duck Typing | |
不在乎你是什麼, 只在乎你會做什麼事 | |
A style of dynamic typing | |
如果真的要檢查type的話, 可以用 | |
if hasattr(x, '__iter__') 用來選擇使用者輸入的type | |
assert hasattr(x, '__iter__'), 'x must be iterable' | |
string 和 integer 都支援 += 這個 operator | |
item vs. items | |
employee vs. employee_name | |
args vs. kargs | |
寫好 Documentation 很重要 | |
Protocol | |
iterator Protocol | |
object which supports __iter__ and next | |
readable | |
object which supports read | |
Weak typing | |
it converts the type if you do an operation not supported with original type | |
python 不是 weak typing ! | |
weak typing 和 dynamic typing 是不同的 | |
Strong typing | |
python 是 strong typing | |
Comprehension | |
list comprehension | |
[i for i in range(10)] # for 的前面是個 exp. 後面是疊代的條件 | |
[i for i in range(10) if i % 2] # [1, 3, 5, 7, 9] | |
[i for i in range(10) if not i % 2] # [0, 2, 4, 6, 8] | |
可以用這樣的方式很快的檢測使用者輸入的資料 | |
可以是巢狀的 | |
generator comprehension | |
(i for i in range(10)) 回傳的值不是 tuple | |
lazy evaluation -> save memory #會等到真的必須要求值的時候才會計算 | |
Other Comprehensions | |
set comprehension | |
set(i for i in range(10)) #python2 or 3 | |
{i for i in range(10)} #python3 only | |
dict Comprehension | |
dict((i,i) for i in range(10)) #python2 or 3 | |
{i:i for i in range(10)} #python3 only | |
Functional Technique | |
any/all function | |
all( i % 2 == 0 for i in seq) # seq 裏面只要有一個條件不符合的話 就會回傳false | |
any( i % 2 == 0 for i in seq) # seq 裏面只要有一個條件符合的話 就會回傳true | |
用 list comprehension 和 any/all 產生 100 內的質數表 | |
[n for n in range(2,100) if not any(n % i == 0 for i in range(2,n))] | |
[n for n in range(2,100) if all(n % i != 0 for i in range(2,n))] | |
寫的時候先考慮後面每個 element 的條件 | |
lamda expression | |
寫法: | |
lambda [args]: [expression] # 其實就是一個小型的 function | |
anonymous function | |
a single expression | |
ex: | |
f = lambda x: g(x)+h(x) | |
do(lambda x, y: (x+y)*(x-y), 10, 20) | |
use sort with lambda | |
ex: # 想要讓 dict 按照 value 的順序排列, 而不是 key 的順序 | |
d = dict(a=300, b=200, c=100) | |
keys = d.keys() | |
keys.sort(key=lambda k: d[k]) | |
for k in keys: | |
print k, d[k] | |
利用 unpack 和 zip 達到轉置矩陣的效果 | |
# example | |
r = [('a', 'b'), ('c', 'd')] | |
r = zip(*r) # 先把 r 拆開, 再重新拼起來 | |
map/filter | |
照著範例打打看@_@" | |
reduce | |
#python3 的 reduce 已經不是 built-in function 要用的話要記得 import | |
兩個兩個運算後回傳結果 | |
partial | |
Closure | |
yield | |
# 用 yield 取代 return 的話, 會回傳 generator -> 可以被疊代, 比較不耗記憶體 | |
co-routine | |
OOP in python | |
bound and unbound method | |
Useful Libray | |
collections | |
re | |
random | |
datetime | |
decimal -> 寫金融軟體的話要用 decimal 不要用 float | |
pickle | |
json | |
timeit -> 對程式做計時, 看效率 | |
doctest | |
pdb -> debugger | |
request -> 拿來送 http request 的, 內建的 urlib 很難用 | |
flask -> a web framework |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment