g87616758 发表于 2018-8-10 12:14:03

python基础4-12764272

  python基础4
  高阶函数
  一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
  sorted函数
  排序也是在程序中经常用到的算法。 无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。通常规定如下,实现从小到大的排序:
  x < y, return -1
  x == y, return 0
  x > y, return 1
  In : t = (12,34,1,24,37)
  In : sorted(t)
  Out:
  In : def reversed_cmp(x,y):###想要实现倒序,则需定义一个函数###
  ...:   if x>y :
  ...:         return -1
  ...:   elif x<y:
  ...:         return 1
  ...:   else:
  ...:         return 0
  ...:
  In : sorted(t,reversed_cmp)
  Out:
  In : li = ['westos','redhat','linux']
  In : sorted(li)
  Out: ['linux', 'redhat', 'westos']###按字母的ASCII码的顺序
  In : li = ['linux','Redhat','westos']
  In : sorted(li)
  Out: ['Redhat', 'linux', 'westos']
  In : li = ['linux','Redhat','westos','redhat']
  In : sorted(li)
  Out: ['Redhat', 'linux', 'redhat', 'westos']
  In : 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 : sorted(li,ignore_case_cmp)
  Out: ['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):
  deff():
  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
  
  
  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
  
  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(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 : 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 : f = open("/home/kiosk/PycharmProjects/pythonbasic/hello","r")
  In : f.read()
  Out: 'python'
  In : f.write
  f.write       f.writelines
  In : 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 : f.write("linux")
  r+:读写模式,依次覆盖源文件内容,写多少覆盖多少,如果文件不存在则报错
  In : f = open("hello","r+")
  In : f.read()
  Out: 'python'
  In : f.close()
  In : f = open("hello","r+")
  In : f.write("westos")
  In : f.read()###此时读的是在覆盖后的下一个位置,因此要想读取该文件,则需要先关闭文件,再打开###
  Out: ''
  In : f.close()
  In : f = open("hello","r+")
  In : f.read()
  Out: 'westos'
  w:可以写入文件内容,不可以读取,如果文件不存在则创建
  In : f = open("lllll","w")
  $ ls
  10.py12.py14.py1.py3.py5.py7.py9.py               hellostack.py
  11.py13.py15.py2.py4.py6.py8.pyfile_operation.pylllll
  w+:可读写,打开文件使直接删除源文件内容,如果文件不存在则创建
  In : f = open('hello','w+')
  In : f.read()
  Out: ''
  In : f.write("world")
  In : f.read()
  Out: ''
  In : f.close()
  In : f = open('hello')
  In : f.read()
  Out: 'world'
  a:写入,文件末尾追加,不可以读,文件不存在则创建
  In : f = open('hello','a')
  In : f.write("hello,hello")
  In : f.close()
  In : f = open('hello')
  In : f.read()
  Out: 'worldhello,hello'
  a+:读写,文件追加,文件不存在则创建
  ###指定读取几个字节###
  In : f = open("hello")
  In : f.read(4)###读取4个字节###
  Out: 'worl'
  ###一行一行的读取###
  In : f = open("hello")
  In : f.readlin
  f.readline   f.readlines
  In : f.readline()
  Out: 'worldhello,hello'
  In : f.readline()
  Out: ''
页: [1]
查看完整版本: python基础4-12764272