Three is the generator ------

Builder

A generator is defined:

Generator is essentially an iterator in python community, most of the time regarded iterators and generators are doing the same concept. Generators and iterators, the only difference is this: Python tools iterator is to provide you with data already written or by converting to come, (such as file handles, iter ([1,2,3]). Generation It is a tool we need to use their own python code build . the biggest difference will be the case.

Second, the configuration of generators

  1. Generator expressions
    1. By function generator
      1. built-in function or module python

Third, the generator function

def func():
    print(11)
    return 22
ret = func()
print(ret)
将函数中的return换成yield,这样func就不是函数了,而是一个生成器函数

def func():
    print(11)
    yield 22
ret = func()
print(ret)   注意:结果 <generator object func at 0x031E5CB0>

执行这个函数的时候,就不再是函数的执行了,而是获取这个生成器对象.
生成器的本质就是迭代器,迭代器如果取值,生成器就如何取值

Fourth, the value generator

def func():
    print(11)
    yield 22
qener = func()  # 这个时候函数不会执行,而是获取到生成器(就是那个内存地址!!)
ret = next(qener) # 这个时候函数才会执行
print(ret)      # 并且yield会将func生产出来的数据 222 给了 ret

并且生成器函数中可以写多个yield
 def func():
     print('11')
     yield 22
     print('33')
     yield 44
 gener = func()
 ret = next(gener)
 print(ret)
 ret2 = next(gener)  # 和迭代器一样,next超过yield的个数就会报错
 print(ret2)

Five difference, yield and return of

  • return generally only a function set, his role is to terminate the function, and a return value of the function's execution, the value returned in the form of a plurality of tuples
  • yield in the generator function may be provided in a plurality, and that he does not terminate function, next will yield the corresponding acquisition element generated value is returned in the form of a plurality of tuples
def eat():
     for i in range(1,10001):
         yield '包子'+str(i)

 e = eat()

 for i in range(200):  # 先吃200个包子
     print(next(e))    # 运行一个next就吃一个包子,非常节省内存,而且可以保留上次的位置

Six, yieldfrom and yield comparison

  • In the python3 provide a iterables each method returns a data generator directly as a result of
 对比 yield 与 yield from
 def func():
     lst = ['卫龙', '老冰棍', '北冰洋', '巧克力']
     yield lst
 g = func()
 print(g)
 print(next(g))  # 只是返回一个列表

 def func1():
     lst = ['卫龙', '老冰棍', '北冰洋', '巧克力']
     yield from lst
 g = func1()
 print(g)  # 它会将这个可迭代对象(列表)的每个元素当成迭代器的每个结果进行返回
 print(next(g))
 print(next(g))
 print(next(g))
 print(next(g))
'''
yield form ['卫龙', '老冰棍', '北冰洋', '巧克力']
等同于:
    yield '卫龙'
    yield '老冰棍'
    yield '北冰洋'
    yield '巧克力'
'''

 def func():
     lst1 = ['卫龙', '老冰棍', '北冰洋', '巧克力']
     lst2 = ['馒头', '花卷', '豆包', '大饼']
     yield from lst1
     yield from lst2
 g = func()
 for i in g:
     print(i)
 因为yield from 是将列表中的每一个元素返回,所以如果写两个yield from 并不会产生交替的效果
 yield from节省代码,提升效率(代替了for循环)

Summary :

  • yield from each iteration is to be a return element, so that if the write does not occur and yield from two alternating effect
  • yield from save code to improve the efficiency of the for loop instead of

Seven, list comprehensions and generator expressions

  1. List derivation formula: Construction of a regular line of code list
    • Circulation mode : [variables (variables after processing) for the variables in interable]
    • Filter Mode : [variables (process variables) for the variable in iterable if Condition] - that is, on the basis of adding a cyclic pattern determination condition, the condition variable is left to the list
一般写法
lst = []
for i in range(10):
    lst.append(i)
print(lst)   #[0,1,2,3,4,5,6,7,8,9,]

列表推导式的循环模式
lst = [i for i in range(10)]  #循环模式
print(lst)   #[0,1,2,3,4,5,6,7,8,9,]

列表推导式的筛选模式
lst = [i for i in range(10) if i % 2==0] #筛选模式
print(lst)   #[0,2,4,6,8]
  1. Generator expressions

    • Generating a list of expressions and formulas derived in exactly the same syntax, as long as the [] with () on it

      gen = (i**2 for i in range(10))
      print(gen)  #生成器内存地址
    • How to trigger generator or iterator

      • next
      • for loop
      • Conversion, such as () with a list converted into lists
    • Inert mechanism generator

      Generator only when accessing the value, put it plainly, you asked him to just give you value, do not look for him to be, he will not be implemented

  2. Generating a list of expressions and the difference derived formula

    • List comprehension memory consuming, once all the data is loaded into memory, generates an iterator expressions compliant protocol, generating an element-by-
    • The resulting values ​​are different, a list of derived type is obtained a list generator expression is obtained by a generator
    • List comprehension at a glance, to generate a memory address just expressions
  3. Dictionary derivations

    lst1 = ['jay', 'jj', 'meet']
    lst2 = ['周杰伦', '林俊杰', 'haven']
    dic = [lst1[i]:lst2[i] for i in range(len(lst1))]
    print(dic)
    # {'jay': '周杰伦', 'jj': '林俊杰', 'meet': 'haven'}
  4. Set derivations

    lst = [1, 2, 3, -1, -3, -7, 9]
    s={i for i in lst}
    print(s)  #{1, 2, 3, 9, -7, -3, -1}

Eight, anonymous functions and built-in functions

  1. Anonymous function: function without a name, lambda

    • Only to build a simple function, function word
    def func(x,y):
     return x+y
    print(func(x,y))
    
    func2 = lambda x,y:x+y  #lambda  定义一个匿名函数
    print(func2(1,2))
    
    func4 = lambda a,b:a if a>b else b
    #匿名函数最常用的就是与内置函数的结合使用
    
  2. Built-in functions: python in there 68 kinds of built-in functions

    1. eval (): coat stripped string and returns the final result, with caution

      s = '5+9'
      print(eval(s))  #14
      
    2. exec (): a code stream execution string, no return value

      s = """
      for i in [1,2,3]:
        print(i)
      """
      exec()
      
    3. hash () Gets an object (the object may be a hash: int, str, bool, tuple,) hash value

    4. help (): function to view detailed description or the module

    5. callable (): used to see whether an object can be called, if it returns True, there are still likely to fail to call, but returns False, then it will not succeed

      name = 'haven'
      def func():
        pass
      print(callable(name))  #False
      print(callable(func))  #True
      
    6. int (): used to convert a string or an integer number

      print(int())  # 0
      print(int('12'))  # 12
      print(int(3.6))  # 3
      
    7. float (): used to convert a string and an integer to floating point

    8. complex (): used to create a complex, or the number or string into a plurality of

    9. bin (): The decimal into binary
    10. oct (): convert decimal to octal string is returned

    11. hex (): to convert decimal to hexadecimal string and returns
    12. divmod (): j calculation result divisor and the dividend, returns a tuple containing the quotient and remainder of (a // b, a% b)

      print(divmod(10,3))   #(3,1)  分页用到
      
    13. round (): retention of floating-point decimal places, default retention integer

      print(round(3.1415926,2))  #3.14 四舍五入 
      
    14. pow (): power demand x ** y

      # 第三个参数为x**y的结果对z取余
      print(pow(2, 3))  # 2**3 8
      print(pow(2, 3, 3)) # 8对3取余 2
      
    15. ord (): Enter the characters to find the position of the character encoding, unicode

    16. chr (): the digital input position to find out the corresponding character, unicode, helpful

    17. repr (): returns a string form object (true colors)

      print(repr('123')) # '123
      
    18. all (): iterables in all True is True

    19. any (): iterables, there is a True True

    20. The following are important !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    21. print (): screen output

      print(1,2,3,sep = '_') #1_2_3 sep设定分隔符,默认空格
      print(1,2,end=' ') # end默认是\n
      
    22. list (): Define or conversion list

      lst = list('asdf')  #括号内可放迭代对象
      # ['a','s','d','f']
      
    23. dic (): Dictionary

      The way to create a dictionary

      dic = {1:'2'}
      dic = {i:1 for i in range(3)}
      dic = dict(one=1,two=2,three=3)
      dic = dict.fromkeys(key,valus)
      
    24. abs (): Gets the absolute value

      print(abs(-10))   #10
      
    25. sum (): sum

      sum(iterable,初始默认值为0)
      print(sum([1, 2, 3, 4])) # 10
      print(sum([1, 2, 3, 4], 10)) # 20
      
    26. max (): find the maximum usage and min () is identical

    27. min (): for the minimum

      print(min([22,3,43,45,3]))  # 2
       lst = [('maqian', 20), ('xihong', 18), ('xiaomi', 22)]
       找年龄最小的元组
      print(min(lst))  #('maqian', 20),按照可迭代对象的第一个元素的第一个字符排序
      
      通过设置key去使用min,key=函数名,返回值是什么就按照什么比较
      min()会自动将可迭代对象的每一个元素作为实参传给函数,最后将遍历的那个元素返回
      
      print(min(lst,key=lambda x:lst[1]))  #使用匿名函数
      
      
    28. reversed (): an iterable reversed, reversing returned iterator

      s = 'maqian'
      for i in reversed(s):
       print(i)  # n a i q a m
      
    29. bytes (): encoding

      s = 'haven'
      print(s.encode('utf-8'))  #第一种方法
      print(bytes(s,encoding='utf-8'))  #第二种方法
      
      编码
      b = b'\xe5\xb0\x8f\xe6\x98\x8e'
      print(b.decode('utf-8'))  # 第一种方法
      print(str(b, encoding='utf-8')) # 第二种方法
      

Guess you like

Origin www.cnblogs.com/douzi-m/p/11234957.html