(http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#id33) 讀完這篇,理解了多一點東西:
知道tuple,comma is the tuple constructor
知道其他編程語言,變量variable是一個box,一個box放一個值,當b=a時,是把a盒子里的值復制給b這個盒子,python中,1是一個integer object,每個object有一個“name”,”tag“,”label“,當a=2,就是把這個”tag“綁到2上,b=a,就是在2再綁一個tag”b”
知道函數默認參數是在函數定義時候執行的,要在runtime執行,需要在內部初始化, 一般用None
def fun(i,a=None): if a is None: a=[] a.append(i) return a知道dict() build-in takes a list of key/value pairs(2-tuple)知道 listcomps, genexps知道 x,y,z=data是 Tuple unpackingcase1: Each dictionary value will be initial a value 0
naive way
mdict={}for (key,price) in data: if key not i n mdict: mdict[key]=0 mdict[key]+=priceclever way: mdict.get(key,default)
mdict={}for (key,price) in data: mdict[key]=(mdict.get(key,0)+price)case2: Each dictionary value will be a list naive way
mdict={}for (key,price) in data: if key in mdict: mdict[key].append(price) else: mdict[key]=[price]this does the job more efficiently mdict={}
for (key,price) in data: mdict.setdefault(key,[]).append(price)more consice and clear
# a list for squares of odd 0-9a=[n**2 for i in range(10) if n%2]想要安裝某一列排序
def my_key(item): return (item[1], item[3])to_sort.sort(key=my_key)You can make your own key function, or use any existing one-argument function if applicable:
str.lower to sort alphabetically regarless of case. len to sort on the length of the items (strings or containers). int or float to sort numerically, as with numeric strings like “2”, “123”, “35”.
新聞熱點
疑難解答