Summary of three artifact and csv file operation

summary

I iterator

  1. What is an iterator

    1. Iterators are container data types
    2. Features: unable to view elements and count the number of elements through the print iterator;
    3. When you need to use an element, you must take the element out of the iterator. After taking it out, the element disappears from the iterator
  2. Create iterator - converts other sequences to iterators

    i1 = iter('hello')
    i2 = iter([10, 20, 30, 40])
    i3 = iter({'a': 10, 'b': 20})
    i4 = iter({100, 200, 300})
    print(i1)       # <str_iterator object at 0x7fc25598fc40>
    print(i2)       # <list_iterator object at 0x7fb21888fc70>
    print(i3)
    print(i4)
    # print(len(i1))        # report errors! TypeError: object of type 'str_iterator' has no len()
    
  3. Get iterator element

    1. No matter how the element of the iterator is obtained, the obtained element will disappear from the iterator
    2. Get single element: next (iterator)

    3. ergodic

      i1 = iter('hello')
      print(next(i1))     # 'h'
      print(next(i1))     # 'e'
      print(next(i1))     # 'l'
      print(next(i1))     # 'l'
      print(next(i1))     # 'o'
      # print(next(i1))     # report errors! StopIteration
      
      result = list(i1)
      print(result)       # []
      
      i1 = iter('hello')
      print(list(i1))     # ['h', 'e', 'l', 'l', 'o']
      # print(next(i1))     # report errors! StopIteration
      
      # 2) Traversal
      i1 = iter('hello')
      for x in i1:
          print(f'x:{x}')
      
      print(list(i1))
      

II generator

  1. What is a generator

    1. A generator is a container, but it does not hold multiple data, but an algorithm that generates (creates) multiple data.
    2. At the same time, it has the characteristics of saving data by iterator: 1 Print invisible content 2 len operation 3 is not supported One element is also one less, and it cannot be put back into the generator
    3. Note: the generator gets the element in the same way as the iterator gets the element
  2. Create generator

    1. Call a function with the yield key to get a generator object.

    2. Note: if there is a yield in the function, calling this function will not execute the function body or obtain the return value of the function, but create a generator object.

      def func1():
          print('hello')
          yield
          return 100
      
      
      result = func1()
      print(result)
      
  3. Control the number and value of data generated by the generator

    The number and value of data generated by the generator are determined by the number of yields encountered when executing the function body and the value after each yield.

    def func2():
        yield 100
        yield 200
        yield 300
    
    
    g1 = func2()
    print(list(g1))     # [100, 200, 300]
    # print(next(g1))   # report errors! StopIteration
    
    
    def func3():
        for x in range(10):
            yield x*2
    
    
    g2 = func3()
    
    # Exercise: create a subject student number generator that can generate student numbers from 'Python 001' to 'Python 999'
    def study_id(subject):
        for x in range(1, 1000):
            yield f'{subject}{x:0>3}'
    
    
    g3 = study_id('python')
    g4 = study_id('java')
    print(next(g3))
    print(next(g4))
    
  4. How the generator creates data

    When calling the function to create the generator, the function body will not be executed. The function will be executed only when the elements in the generator are obtained through the generator object. Each time the function body is executed, it will only stop when it reaches yield, and the stop position will be recorded. The next time the elements are obtained, it will be executed from the last end position.

    def func4():
        print('======1======')
        yield 100
        print('======2======')
        yield 200
        print('======3======')
        yield 300
    
    
    g4 = func4()
    print(next(g4))
    print(next(g4))
    print(next(g4))
    
    
    def func5():
        yield 100
        yield 200
        yield 300
    
    
    # print(next(func5()))        # 100
    # print(next(func5()))        # 100
    g5 = func5()
    print(next(g5))
    print(next(g5))
    

III Decorator (understand)

  1. Decorator - decorators are used to add functionality to functions

  2. The routine of writing decorators

    """
    def Decorator name(f):
        def new_f(*args, **kwargs):
            Realize new functions
            result = f(*args, **kwargs)
            Realize new functions
            return result
        return new_f  
    """
    

IV csv file operation

  1. csv file read operation

    1. The iterator gets the content of each element in the list

      # a. Create reader object: CSV Reader (file object) - create the reader corresponding to the file and get the file content
      # Note: when opening a csv file, you need to assign an empty string to the parameter newline
      # f = open('files/2018 Beijing points settlement data. csv', encoding='utf-8', newline = '')
      reader1 = csv.reader(open('files/2018 Settlement data of points in Beijing in.csv', encoding='utf-8', newline=''))
      
      # b. Get the contents of the file through the reader object, which is essentially an iterator
      print(next(reader1))     # ['id', 'name', 'birthday', 'company', 'score']
      print(list(reader1))
      
    2. Method 2 - read the contents of the file to get an iterator. The elements in the iterator are the dictionary corresponding to each row of content (the key is the first row of data in each column)

      reader2 = csv.DictReader(open('files/2018 Settlement data of points in Beijing in.csv', encoding='utf-8', newline=''))
      for x in reader2:
          print(x)
      
  2. csv file write operation

    1. Method 1 - write a row of data in list units

      # a. Create writer object: CSV Writer (file object)
      writer1 = csv.writer(open('files/students.csv', 'w', encoding='utf-8', newline=''))
      
      # b. Write data
      # writer object Writerow - write one row at a time
      # writer object Writerows (elements are lists of lists) - write multiple rows of data at the same time
      writer1.writerow(['Student number', 'full name', 'Age', 'Telephone', 'fraction'])
      writer1.writerows([
          ['stu001', 'Xiao Ming', 19, '110', 98],
          ['stu002', 'Zhang San', 23, '199', 72],
          ['stu003', 'floret', 22, '1728', 78]
      ])
      
    2. Method 2 - write a row of data in dictionary units

      # a. Create DictWriter object: CSV DictWriter (file object, dictionary key)
      writer2 = csv.DictWriter(
          open('files/dogs.csv', 'w', encoding='utf-8', newline=''),
          ['Dog name', 'Age', 'varieties', 'Price']
      )
      
      # b. Write the key of the dictionary to the first line of the file as the content of the file
      writer2.writeheader()
      
      # c. Write data
      # writer object Writerow - write one row at a time
      # writer object Writerows (element is a list of dictionaries) - write multiple rows of data at the same time
      writer2.writerow({'Dog name': 'Wangcai', 'Age': 3, 'varieties': 'a pug', 'Price': 500})
      writer2.writerows([
          {'Dog name': 'Guess', 'Age': 2, 'varieties': 'Siberian Husky', 'Price': 1500},
          {'Dog name': 'potato', 'Age': 1, 'varieties': 'Earth dog', 'Price': 50},
          {'Dog name': 'Niu Niu', 'Age': 3, 'varieties': 'Golden hair', 'Price': 2500}
      ])
      

Keywords: Python

Added by Code_guy on Thu, 10 Mar 2022 11:48:35 +0200