#list
1 2 3 4 5 6 7
| classmates=['jack','Bob'] len(classmates) list.append('xx') list.insert(1,'xx') list.pop() list.pop(1)
|
#tuple, list的[]变为(),元素不可变
1 2 3
| classmates=('jack','Bob') t = (1,)
|
#if
1 2 3 4 5 6
| if xx: do some thing elif xx: do some thing else: do some thing
|
#关于raw_input
1 2
| a = int(raw_input('xx'))
|
#dict
1 2 3 4 5
| d={'a':100,'b':75,'c':50} d.get('a') d.get('a',x) d.pop('a')
|
#set
1 2 3 4
| s = set([1,2,3]) s.add(4) s.remove(4) s1 & s2
|
#函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| def my_abs(x): if x >= 0: return x else: return -x #空函数 def nop(): pass #类型检查 def my_abs(x): if not isinstance(x,(int,float)): raise TypeError('bad operand type') #do some thing #返回多个值 def func() return 1,2 #默认参数必须指向不变的对象!不然函数体可能会变 #可变参数 def getsum(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum #关键字参数 def person(name, age, **kw): print 'name:',name,'age:',age,'other:',kw #参数可以组合,顺序必须是:必选参数,默认参数,可变参数,关键字参数 def func(a, b, c = 0,*args, **kw): xxx #*args是可变参数,接收的是tuple #**kw是关键字参数,接收的是dict
|
#切片
#迭代
1 2 3 4 5 6 7 8 9
| d = {'a':1,'b':2,'c':3} for key in d: print key for value in d.itervalues(): xxx from collections import Iterable isinstance('abc',Iterable)
|
#列表生成式
1 2 3 4 5 6 7 8 9 10 11 12
| range(1,11) [x * x for x in range(1,11)] [x * x for x in range(1,11) if x % 2 == 0] [m + n for m in 'ABC' for n in 'XYZ'] import os [d for d in os.listdir('.')] d={'a':1,'b':2} [k + '=' + v for k, v in d.iteritems()] [s.lower() for s in L]
|
#生成器,按照函数先生成一部分
1 2 3 4 5 6 7 8 9 10 11 12 13
| g = (x * x for x in range(10)) g.next() for n in g: print n def fib(max): n,a,b = 0,0,1 while n < max: yield b a,b = b,a+b n = n + 1
|
#map and reduce
1 2 3 4 5 6 7 8 9
| def add(x,y): return x+y reduce(add, [1,3,5,7,9]) def str2int(s): def fn(x,y): return x * 10 + y return reduce(fn,map(int,s))
|
#排序
1 2 3
| sorted([1,3,2,5,4]) sorted([1,2,4],cmp)
|
#匿名函数
1 2 3 4
| map(lambda x: x*x, [1,2,3]) f = lambda x : x*x
|
#decorator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def log(func): def wrapper(*args, **kw): print 'call %s():' %func.__name__ return func(*args, **kw) return wrapper @log def now(): print 'xx' def log(func): @functools.wraps(func) def wrapper(*args, **kw): print 'call %s():' %func.__name__ return func(*args, **kw) retrun wrapper
|
#偏函数
1 2
| import functools int2 = functools.partial(int, base=2)
|
#模块
1 2
| import cStringIO as StringIO
|
#gevent 协程
1 2 3 4 5 6 7 8 9 10 11
| from gevent import monkey; monkey.patch_socket() import gevent def func(n): xxx g1 = gevent.spawn(func, 1) g2 = gevent.spawn(func, 1) g1.join() g2.join()
|
#pack and unpack
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| pack(fmt, v1, v2, ...) unpack(fmt, string) calcsize(fmt) string.maketrans(from, to) string.translate(s, table[, deletechars]) str.translate(table[, deletechars])
|