python基础4
高阶函数
一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
sorted函数
排序也是在程序中经常用到的算法。 无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。通常规定如下,实现从小到大的排序:
x < y, return -1
x == y, return 0
x > y, return 1
In [1]: t = (12,34,1,24,37)
In [2]: sorted(t)
Out[2]: [1, 12, 24, 34, 37]
In [4]: def reversed_cmp(x,y):###想要实现倒序,则需定义一个函数###
...: if x>y :
...: return -1
...: elif x<y:
...: return 1
...: else:
...: return 0
...:
In [5]: sorted(t,reversed_cmp)
Out[5]: [37, 34, 24, 12, 1]
In [6]: li = ['westos','redhat','linux']
In [7]: sorted(li)
Out[7]: ['linux', 'redhat', 'westos']###按字母的
In [8]: li = ['linux','Redhat','westos']
In [9]: sorted(li)
Out[9]: ['Redhat', 'linux', 'westos']
In [10]: li = ['linux','Redhat','westos','redhat']
In [11]: sorted(li)
Out[11]: ['Redhat', 'linux', 'redhat', 'westos']
In [13]: 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
....:
In [14]: sorted(li,ignore_case_cmp)
Out[14]: ['linux', 'Redhat', 'redhat', 'westos']
#函数作为返回值()
def wrap_sum(*args):
def my_sum():
sum_num = 0
for i in args:
if not isinstance(i,(int,float)):
print "Error Type"
sum_num = sum_num +i
return sum_num###返回的函数名不加括号,就返回该函数的地址###
return my_sum
f = wrap_sum(1,2,3,6)
#print f
print f()###要想调该函数的值,则需要加括号####
f1 = wrap_sum(1,2,3,6)###传递的参数一样,但是函数地址是不一样的,每次调用都是调用一个新函数####
print f1
f2 = wrap_sum(1,2,3,6)
print f2
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
12
<function my_sum at 0x8f0a28>
<function my_sum at 0x8f0aa0>
Process finished with exit code 0
def count():
fs = []
for i in range(1,4):
def f():
return i*i
fs.append(f)###将f的地址加入列表fs###
return fs###返回的是三个地址###
f1,f2,f3 = count()###调用count()函数,即将返回的三个地址分别给了f1,f2,f3###
print f1()
print f2()
print f3()
###但是执行结果均为9###
改进:
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()
print f1()
print f2()
print f3()
执行结果:
1
4
9
####匿名函数###
当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。
关键字 lambda 表示匿名函数,冒号前面的 x 表示函数参数,冒号后表示要返回的值
1 匿名函数不需要函数名,可以避免函数名的冲突
2 匿名函数可以跳过给函数分配栈空间
def pow1(x):
return x*x
print map(pow1,range(1,11))
print map(lambda x:x*x,range(1,11))
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Process finished with exit code 0
3 匿名函数可以赋值给一个变量,需要运行时,变量名()
print lambda :1###打印了匿名函数的地址###
f = lambda :1###将地址赋值给变量##
print f()###运行结果###
执行结果:
<function <lambda> at 0x13059b0>
1
###匿名函数传递必选参数和默认参数###
f = lambda x,y=2:x**y
print f(2,3)
print f(2)
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
8
4
Process finished with exit code 0
###匿名函数传递可变参数###
f = lambda *x:map(lambda x:x*x,x)
print f(1,2,3,4)
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
[1, 4, 9, 16]
Process finished with exit code 0
###匿名函数传递关键字参数###
f = lambda **kwargs:kwargs.items()
print f(name="fentiao",age=5)
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
[('age', 5), ('name', 'fentiao')]
Process finished with exit code 0
练习:利用匿名函数和字典重新编辑计算器的代码
x =input("num1:")
oper = raw_input("oper:")
y = input("num2:")
d ={
"+":lambda x,y:x+y,
"-":lambda x,y:x-y,
"*":lambda x,y:x*y,
"/":lambda x,y:x/y
}
if oper not in d.keys():
print "Error"
print d[oper](x,y)
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
num1:3
oper:+
num2:4
7
Process finished with exit code 0
In [2]: print 1 if 1>2 else 2###判断1是否大与2,若大与则返回1,小与则返回2
2
####装饰器####
用来装饰函数的函数
1 不修改函数的源代码
2 函数的调用方式没有改变
###准备###
def hello():
print "hello..."
hello1()
def hello1():
print "hello1..."
hello()
####计算程序执行时间###
import time###导入模块###
def timmer(func):
start_time = time.time()
func()
stop_time = time.time()
return stop_time-start_time
def hello2():
print "hello2..."
time.sleep(2)###停2s###
print timmer(hello2)
###不改变调用方式###
import time
def timmer(func):
def dec():
start_time = time.time()
func()
stop_time = time.time()
return stop_time-start_time
return dec
def hello2():
print "hello2..."
time.sleep(2)
hello2=timmer(hello2)
hello2()
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
hello2...
Process finished with exit code 0
###装饰器###
import time
def timmer(func):
def dec():
start_time = time.time()
func()
stop_time = time.time()
return stop_time-start_time
return dec
@timmer ###相当于hello2=timmer(hello2),语法糖###
def hello2():
print "hello2..."
time.sleep(2)
print hello2()
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
hello2...
2.00218486786
Process finished with exit code 0
###写一个装饰器实现hello2()函数的日志,日志内容为hello()的内容以及执行时间###
import time
def timmer(func):
def dec():
start_time = time.time()
func()
stop_time = time.time()
return "%s run %f s"%(func.__name__,stop_time-start_time)
return dec
@timmer ###hello2=timmer(hello2),语法糖
def hello2():
print "hello2..."
time.sleep(2)
print hello2()
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/15.py
hello2...
hello2 run 2.002128 s
Process finished with exit code 0
###对文件进行操作###
f = open("hello")###打开文件###
print f.read()###读文件###
f.close()###关闭文件###
f = open("hello",'w')###以写方式打开,此时不能进行读操作###
f.write("python")###会将文件内容覆盖为”python“
f.close()###关闭文件###
执行结果:
其他的几种模式:
r:可以读取文件内容,不可以写入,如果文件不存在则报错
In [4]: f = open("/home/kiosk/PycharmProjects/pythonbasic/hello","r")
In [5]: f.read()
Out[5]: 'python'
In [6]: f.write
f.write f.writelines
In [6]: f.write("linux")###不可以写入###
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-6-18e05364d061> in <module>()
----> 1 f.write("linux")
IOError: File not open for writing
In [7]: f.write("linux")
r+:读写模式,依次覆盖源文件内容,写多少覆盖多少,如果文件不存在则报错
In [1]: f = open("hello","r+")
In [2]: f.read()
Out[2]: 'python'
In [3]: f.close()
In [4]: f = open("hello","r+")
In [5]: f.write("westos")
In [6]: f.read()###此时读的是在覆盖后的下一个位置,因此要想读取该文件,则需要先关闭文件,再打开###
Out[6]: ''
In [7]: f.close()
In [9]: f = open("hello","r+")
In [10]: f.read()
Out[10]: 'westos'
w:可以写入文件内容,不可以读取,如果文件不存在则创建
In [12]: f = open("lllll","w")
[kiosk@foundation38 pythonbasic]$ ls
10.py 12.py 14.py 1.py 3.py 5.py 7.py 9.py hello stack.py
11.py 13.py 15.py 2.py 4.py 6.py 8.py file_operation.py lllll
w+:可读写,打开文件使直接删除源文件内容,如果文件不存在则创建
In [13]: f = open('hello','w+')
In [14]: f.read()
Out[14]: ''
In [17]: f.write("world")
In [18]: f.read()
Out[18]: ''
In [19]: f.close()
In [20]: f = open('hello')
In [21]: f.read()
Out[21]: 'world'
a:写入,文件末尾追加,不可以读,文件不存在则创建
In [22]: f = open('hello','a')
In [23]: f.write("hello,hello")
In [25]: f.close()
In [27]: f = open('hello')
In [28]: f.read()
Out[28]: 'worldhello,hello'
a+:读写,文件追加,文件不存在则创建
###指定读取几个字节###
In [36]: f = open("hello")
In [37]: f.read(4)###读取4个字节###
Out[37]: 'worl'
###一行一行的读取###
In [40]: f = open("hello")
In [41]: f.readlin
f.readline f.readlines
In [41]: f.readline()
Out[41]: 'worldhello,hello'
In [42]: f.readline()
Out[42]: ''
本文转自blueclo51CTO博客,原文链接:http://blog.51cto.com/12774272/1947895 ,如需转载请自行联系原作者