python basic learning day12 generator and derivation

Keywords: Python less REST

Add: the function cannot change the global immutable variable, and the variable variable can still be changed.

l1 = [1,2]
def a(l1):
    l1.pop(1)
a(l1)
print(l1)
  1. generator

    1. Generator: the python community regards generator and iterator as the same kind, and the essence of generator is iterator. The only difference is that the generator is the data structure that we build with Python code, and the iterator is provided or transformed by python.

    2. Get the generator by:

      • generator function
      • Generator Expressions
      • Provided inside python.
    3. Generator function get generator, yield:

      def func():
          print(1)
          print(3)
          yield 5
      print(func)    #< function function function at 0x000001a3cca04438 > is still a function
      ret = func()
      print(ret)    #<generator object func at 0x000002471A631D48>
      #generator object#Generator object
      
      def func():
          print(3)
          yield 5
      ret = func()
      print(next(ret))   #3 5
      
      #Return value of a next to a yield
      def func():
          print(3)
          yield 5
          yield 7
      print(next(func()))   #3 5
      
    4. yield and return

      Return: only one return end function call can exist in a function, and return a value to the function's executor.

      Yield: as long as there is a yield in the function, it is a generator function. There can be multiple yield in the generator function. A next return value to a yield will not end the function call, but return will end the function call.

      #For example:
      def func():
          for i in range(1000000):
              yield i
      ret = func()
      i = 1000000
      while i >= 0:
          print(next(ret))
          i -= 1
      
    5. If you call yield again, it will follow the previous next

      def func():
          for i in range(1000000):
              yield i
      ret = func()
      for i in range(5):
          print(next(ret))
         
      for i in range(10):
          print(next(ret))
      #0, 2,3,4,5,6,7,8,9,10,11,12,13,14
      
    6. Yield from (after version 3.4): turn the data into an iterator to return

      def func():
          l1 = [1,2,3,4,]
          yield l1
      print(next(func()))
      #[1, 2, 3, 4]
      
      def func():
          l1 = [1,2,3,4,]
          yield from l1     #Turn this list into an iterator and return
      print(next(func()))
      #1
      print(nex(func()))
      #2
      
    7. Generator functions can use for loops directly:

      def func():
          l1 = [1,2,3]
          yield from l1
      for i in func():
          print(i)   #1 2 3 
      
  2. List derivation, generator expression:

    • List derivation: use a line of code to build a more complex and regular list.

      l1 = [i for i in range(10)]  #You can change range to an iterative object.
      
    • There are two types of list derivation.

      • Loop mode: each element needs to be traversed. [variable (processed variable) for variable in iterable]

        #Example 1: write the square of all integers within 10 to the list:
        l1 = [i*i for i in range(11)]
        print(l1)
        
        #Example 2: all odd numbers within 100 are written to the list:
        l1 = [i for i in range(1,100,2)]
        print(l1)
        
        #Example 3: write list from python1 to python10:
        l1 = [f'python{i}' for i in range(1,11)]
        print(l1)
        
      • Filter mode: [variable (processed variable) for variable in iterable if condition]

        #Example 1: write the number within 10 that can be divided by 2 to the list
        l1 = [i for i in range(11) if i%2==0]
        print(l1)
        
        #Example 2: filter the strings less than 3 in list L1, and convert the rest to uppercase. l1 = ['nonl','globals','as','in']
        l1 = ['nonl','globals','as','in']
        l2 = [i.upper() for i in l1 if len(i)>=3]
        print(l2)
        
        #Example 3: generate a new list from a string with two zeros in the num list. num = [['021','001','201'],['100','012','010']]
        l1 = [j for i in num for j in i if j.count('0') == 2]
        print(l1)
        
    • Generator expression: almost the same as list derivation, the generator has loop mode and filter mode, only changing [] to (). But it saves more space than list derivation.

      l1 = (i for i in range(10))
      print(l1)
      #<generator object <genexpr> at 0x000001BB028F8CC8>
      print(next(l1))   #0
      
      l1 = (i for i in range(10))
      for i in l1:    #You can use the for loop directly, because the for loop itself changes an iteratable object into an iterator loop.
          print(i)
      
    • List derivation

      • Disadvantages:
        1. Only the complicated and regular list can be built;
        2. It is not recommended to use list derivation if more than three layers of loops can be constructed successfully;
        3. Unable to find error (debug mode)
    • Dictionary derivation

      l1 = ['1','2','3']
      l2 = ['One','Two','Three']
      dic = {l1[i]:l2[i] for i in range(len(l1))}
      
    • Set derivation

      set1 = {i for i in range(10)}
      
  3. Built in functions:

    • python provides 68 built-in functions.

      • First level difficulty: abs() enumerate() filter() max() min() open() range() print() len() list() dict() str() float() reversed() set() sum() tuple() type() zip() dir()
      • Second level difficulty: classmethod() delattr() getattr() issubclass() isinstance() object() property() setattr() staticmethod() super()
      • Three levels of difficulties: all() any() bytes() callable() chr() complex() divmod() eval() exec() format() fromset() globals() hash() help() id() input() int() locals() next() oct() ord() pow() repr() round()
    • eval(): strip the outer layer (quotation mark) of string, operate the code inside, and return value. It's better not to use it at work. It's easy to get virus.

      s1 = '1+1'
      print(s1)   #1+1
      print(eval(s1),type(eval(s1)))  #2 <class 'int'>
      
    • exec(): almost the same as eval(), but it deals with code flow. It's better not to use it at work. It's easy to get virus.

      msg = """
      for i in range(5):
      	print(i)"""
      exec(msg)   #0,1,2,3,4
      
    • Hash: gets the hash value of an object (hash object: int,str,bool,tuple).

      • Hash value: a hash value is required between encryption algorithms, which is related to the hash algorithm.
      print(hash('12'))
      
    • help(): print / get the usage of an object.

      print(help(str))
      
      print(help(str.upper))
      
    • callable(): judge whether an object can be called. True is true, False is False.

      l1 = [1,2]
      def func():
          pass
      print(callable(l1))  #False
      print(callable(func))   #True
      

      The remaining built-in functions are updated later.

Posted by dbrimlow on Thu, 26 Mar 2020 02:07:41 -0700