標籤:
0. 新與舊
兩種reverse
>>> L = [1,2,3,4]>>> R = L[::-1] # new object>>> R[4, 3, 2, 1]>>> L.reverse() # in place>>> L[4, 3, 2, 1]>>>
兩種sort
>>> sorted(r) # new object[’black’, ’blue’, ’green’, ’red’, ’white’]>>> r[’white’, ’black’, ’green’, ’blue’, ’red’]>>> r. sort() # in-place>>> r[’black’, ’blue’, ’green’, ’red’, ’white’]
1. 函數參數
def f(a, b, c=0, *argc, **kw):
print a, b, c, argc, kw
>>> f(1, 2, 3, ‘a‘, ‘b‘, ‘c‘, key=‘value‘)
1 2 3 (‘a‘, ‘b‘, ‘c‘) {‘key‘: ‘value‘}
a, b為必選參數,c預設參數,argc可變參數,kw為關鍵字參數。傳入函數時,argc是一個tuple,kw為dict。
注意預設參數,一定要指向不可變變數。否者多個函數的同一參數可能指向同一個instance
>>> def foo(bar=[]): ... bar.append("baz") ... return bar>>> foo()["baz"]>>> foo()["baz", "baz"]>>> foo()["baz", "baz", "baz"]>>> def foo(bar=None):... if bar is None: # or if not bar:... bar = []... bar.append("baz")... return bar...>>> foo()["baz"]>>> foo()["baz"]>>> foo()["baz"]
2. 迭代
>>> from collections import Iterable>>> isinstance(‘string‘, Iterable)True>>> isinstance([1,2,3], Iterable)True>>> isinstance(123, Iterable)False
>>> for i, v in enumerate([‘a‘, ‘b‘, ‘c‘]):... print i, v...0 a1 b2 c>>>
>>> for i, j in zip([1,2,3], [‘a‘, ‘b‘, ‘c‘]):... print i, j...1 a2 b3 c
3. List Comprehension中的if-else
>>> L = [‘We‘, ‘are‘, 42, ‘ALONE‘, ‘!‘]>>> [s.lower() if isinstance(s,str) else s for s in L][‘we‘, ‘are‘, 42, ‘alone‘, ‘!‘]
4. class
http://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
限定class的成員
__slots__
>>> class Student(object):... __slots__ = (‘name‘, ‘age‘) ...
5. exception
檢查多個異常,需要放在tuple內
>>> try:... l = ["a", "b"]... int(l[2])... except (ValueError, IndexError) as e: ... pass...>>>
一些Python知識點