一,高级特性:
1,切片:[start:stop:step]
>>>l=range(6) >>>l[3,-1,2] resulte is [3]
2,迭代
2.1按itervalues()
>>> d={1:2,2:3,3:4} >>> for k in d: ... print k,d[k] ... 1 2 2 3 3 4
2.2 按iteritems()
>>> for v in d.iteritems(): ... print v ... (1, 2) (2, 3) (3, 4) 以元组形式返回
2.3 带索引输出:enumerate
>>> for i,value in enumerate([‘a‘,‘b‘,‘c‘]): ... print i,value ... 0 a 1 b 2 c
2.4 生成器:一边循环一边计算的机制,称为生成器(Generator),有利于节省存储空间,相当于链表中next
>>> def fib(max): ... n,a,b=0,0,1 ... while n<max: ... yield b ... a,b=b,a+b ... n=n+1 ... >>> fib(6) <generator object fib at 0x7f7f3c2b94b0> >>> for i in fib(6): ... print i ... 1 1 2 3 5 8
(二),函数式编程
1,高阶函数:函数名当作方法的参数变量
>>> def add(x,y,abs): ... return abs(x)*abs(y) >>> def cut(x,add): ... return x-add(x,x,abs) ... >>> cut(1,add) 0
2,map
把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字 map(lambda s :s.capitalize(),[‘AC‘,‘ac‘] [Ac,Ac]
reduce:
>>> l=map(lambda s:s.capitalize(),[‘AC‘,‘ac‘]) >>> reduce(lambda x,y:x+y,l) ‘AcAc‘
filter:
>>> import math >>> def isPrim(s): ... for i in range(2,int(math.sqrt(s)+1)): ... if s%i==0: ... return False ... return True ... >>> filter(isPrim,range(2,10)) [2, 3, 5, 7] >>> import time >>> print time.mktime(time.localtime())//时间计算 1497605034.0
3,sorted x>y 1,x<y -1 x==y 0
sorted([1,3,2],lambda x,y:y-x) //如果y-x>0则两个数交换位置,使用冒泡排序 [3, 2, 1]
4,闭包(Closure),使用返回函数形式:
def count(): fs=[] for i in range(1,4) def f(j): def g(): return j*J return g fs.append(f(i)) return fs for i in count(): print i,j
5,匿名函数:lambda
6,“装饰器”(Decorator):对方法进行增强说明,但有不去改变方法
import functools def log(args): """""" task = "call" def actual_log(func): @functools.wraps(func) def wrapper(*args,**kw): print ‘%s:%s()‘ % (task,func.__name__)//两个下划线 return func(*args, **kw) return wrapper if hasattr(args,‘__call__‘): return actual_log(args) else: task = args return actual_log @log def f(): pass @log("execute") def e(): pass
5,偏函数
>>> max2=functool.partial(max,10) //10作为*args的一部分自动加到左边 >>> max2(1,3,4,5) 10>>> def func(a,b,c):>>> print a,b,c>>>func2=functools.partial(func,b=3) 替换关键参数>>>func(1,c=4)1 3 4
时间: 2024-10-28 11:02:59