#######sorted高阶函数#######
#!/usr/bin/env python#coding:utf-8
_author_ = 'hxr'
li=['hhh','ddd','BB','LL']
num=[12,2,1,43,23]
###数字由大到小进行排序
def reserved_cmp(x,y):if x>y:
return -1
elif x<y:
return 1
else:
return 0
print sorted(num)
print sorted(num,reserved_cmp)
##忽略大小写进行排序
def ignore_case_cmp(x,y):lower1 = x.lower()
lower2 = y.lower()
if lower1<lower2:
return -1
elif lower1>lower2:
return 1
else:
return 0
print sorted(li,ignore_case_cmp)
print sorted(li)
######################
#!/usr/bin/env python#coding:utf-8
_author_ = 'hxr'
#函数作为返回值
def wrap_sum(*args):
def my_sum():
sum_num=0
for i in args:
if not isinstance(i,(int,float)):
print 'ERROR'
sum_num+=i
return sum_num
return my_sum
f=wrap_sum(2,3,1,4)
print f()
###########函数作为返回值############
#!/usr/bin/env python#coding:utf-8
_author_ = 'hxr'
def count():
fs=[]
for i in range(1,4):
def f():
return j*j
fs.append(f(i))
return fs
f1,f2,f3=count()##存放函数f的地址,此时i均为3
print f1()
print f2()
print f3()
执行结果:9 9 9
#!/usr/bin/env python
#coding:utf-8
_author_ = 'hxr'
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
f1,f2,f3=count()##存放函数g的地址,j分别记录i值
print f1()
print f2()
print f3()
执行结果:1,4,9
#########匿名函数##############
##可变参数#!/usr/bin/env python
#coding:utf-8
_author_ = 'hxr'
f=lambda *x:map(lambda x:x*x,x)
print f(1,2,3,4)
###关键字参数
f1=lambda **kwargs:kwargs.items()
print f1(name='hello',age=3)
##无参数
f2=lambda :1
print f2()
##多个参数
f3=lambda x,y=2:x**y
print f3(2,3)
print f3(2)
##运算器
c1=lambda x,y:x+y
c2=lambda x,y:x-y
c3=lambda x,y:x*y
c4=lambda x,y:x/y
x=input('输入一个数:')
y=input('输入一个数:')
oper=raw_input('输入对应操作:')
d={'+':c1(x,y),'-':c2(x,y),'*':c3(x,y),'/':c4(x,y)}
if oper not in d.keys():
print "输入操作有误"
exit(0)
print d[oper]
#############装饰器##############
#1).不修改函数的源代码#2).函数的调用方式没改变
#!/usr/bin/env python
#coding:utf-8
_author_ = 'hxr'
import time
def timmer(func):
def dec():
start_time=time.time()
func()
stop_time=time.time()
print '%s run %s 秒'%(func.__name__,stop_time-start_time)
return func.__name__,stop_time-start_time
return dec
@timmer # hello1=timmer(hello1),语法糖(相当于这条语句)
def hello1():
print 'hello1...'
time.sleep(2)
hello1()
########文件操作######
##将一个文件的hello全部替换westos,并另编辑文件存储#!/usr/bin/env python
#coding:utf-8
_author_ = 'hxr'
f=open('hello','a+')
s=f.read()
s=s.replace('hello','westos')
with open('hello.bak','w') as g:
g.write(s)
f.close()