(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”.
新闻热点
疑难解答