zoukankan      html  css  js  c++  java
  • 闭包,生成器,迭代器

    闭包

    函数内部再定义一个函数并且这个函数用到了外边的函数的变量,那么将这个函数以及用到的一些变量称为闭包。

    • 闭包作用:提高代码可复用性。
    def line_conf(a,b):
    	def line(x):
    		return a*x + b
    	return line
    	
    line1 = line_conf(1,1)
    line2 = line_conf(4,5)
    print(line1(5))
    print(line2(5))
    

    生成器

    在Python 中,这种一遍循环一遍计算的机制,称为生成器: generator,节省大量的空间。

    可以通过next()函数获得生成器的下一个返回值。

    1. 创建生成器

      G = (x*2 for x in range(5))
      >>>G
      >>><generator object <genexpr> at 0x7f626c132db0>
      
    2. 斐波拉契数列

      著名的斐波拉契数列(Fibonacci),除第⼀个和第⼆个数外,任意⼀
      个数都可由前两个数相加得到:
      
      def fib(times):
      	n = 0
      	a,b = 0,1
      	while n<times:
      		yield b
      		a,b = b,a+b
      		n+=1
      	return 'done'
      
      >>>F=fib(5)
      >>>next(F)
      >>>1
      
    3. 捕获Stoplteration

      while True:
      	try:
      		x = next(g)
      		print("value:%d"%x)
      	except StopIteration as e:
      		print("生成器返回值:%s"%e.value)
      		break
      
      value:1
      value:1
      value:2
      value:3
      value:5
      生成器返回值:done
      
    4. send

      例子:执行到yield时,gen函数作⽤暂时保存,返回i的值;temp接收下次
      c.send("python"),send发送过来的值,c.next()等价c.send(None)
      
      def gen():
      	i = 0
      	while i <5:
      		temp = yield i
      		print(temp)
      		i+=1
      
      In [45]: f.send('haha')
      haha
      Out[45]: 1
      

    可迭代对象

    直接作用于for 循环的数据类型:

    1、是集合数据类型,如list、tuple、dict、set、str等;

    2、generator,包括生成器和带yield的generator function

    作用于for循环的对象都是可迭代对象: iterable

    1. 判断是否可以迭代

      可以使用isinstance()判断一个对象是否是iterable对象:
      from collections import Iterable
      In [51]: isinstance([], Iterable)
      Out[51]: True
      In [52]: isinstance({}, Iterable)
      Out[52]: True
      
      

    迭代器

    • 可以被next()函数调用并不断返回下一个值的对象称为迭代器: iterator

    • isinstance() 判断一个对象是否是 iterator 对象

      In [56]: from collections import Iterator
      In [57]: isinstance((x for x in range(10)), Iterator)
      Out[57]: True
      In [58]: isinstance([], Iterator)
      Out[58]: False
      
    • iter()函数

      生成器都是iterator 对象,但是list,dict,str虽然是iterable,却不是iterator

      把list、dict、str等iterable 变成iterator 可以使用iter()函数

      In [62]: isinstance(iter([]), Iterator)
      Out[62]: True
      In [63]: isinstance(iter('abc'), Iterator)
      Out[63]: True
      

    总结

    • 凡是可以作用于for循环的对象都是iterable类型
    • 凡是可作用于next()函数的对象都是iterator类型
    • 集合数据类型如list、dict、str等是iterable但不是iterator,不过可以通过iter()函数获得一个iterator对象。
  • 相关阅读:
    类,对象和方法
    jmeter对接口测试入参进行MD5加密
    Jmeter配置代理进行录制
    MYSQL——having 和 where的区别
    MySQL
    Python——面试编程题
    mysql——面试题
    Vue——解决跨域请求问题
    Vue——axios网络的基本请求
    ES6 数组map(映射)、reduce(汇总)、filter(过滤器)、forEach(循环迭代)
  • 原文地址:https://www.cnblogs.com/sunjingjingking/p/10203464.html
Copyright © 2011-2022 走看看