Python anonymous functions, generators, built-in functions, derivation

Table of Contents

Day13: Built-in functions, generators and derivation

13.1 Anonymous functions

13.2 Generator

13.3 Built-in functions

13.4 Derivation


Day13: Built-in functions, generators and derivation

13.1 Anonymous function

An anonymous function is based on a lambda expression to define a function that can have no name. The format is: lambda parameter: function body

Due to restrictions, the function body can only write one line, so anonymous functions are suitable for simple business processing and can quickly and easily create functions

  • Parameters, supports any parameters.

    lambda x: function body
    lambda x1,x2: function body
    lambda *args, **kwargs: function body
  • The function body can only support a single line of code.

    def xxx(x):
        return x + 100
        
    lambda x: x + 100
  • Return value, by default, the result of the execution of a single line of code in the function body is returned to the execution part of the function.

    func = lambda x: x + 100
    ?
    v1 = func(10)
    print(v1) # 110

Supplementary expansion: ternary operations

Simple conditional statements can be implemented based on ternary operations, for example:

func = lambda x: "bigger" if x > 66 else "smaller"
?
v1 = func(1)
print(v1) # "Small"
?
v2 = func(100)
print(v2) # "Big"

Note: lambda expressions and ternary operations have nothing to do with each other and are two independent knowledge points.

13.2 Generator

  • The writing method created by the function + yield keyword can help us save memory under certain circumstances.

  • The characteristic is: the execution position in the function is recorded. The next time next is executed, it will continue to execute downwards from the previous position.

def func():
    print(111)
    yield 1
?
    print(222)
    yield 2
?
    print(333)
    yield 3
?
    print(444)
    #When return is encountered at the end or in the middle, the program explodes: StopIteration error
data = func()
?
# Execute the generator function func and return the generator object.
# Note: When the generator function is executed, the code inside the function will not be executed.
# Use the generator function normally and use a for loop (no error will be reported when it ends)
data = func()
?
for item in data:
    print(item)

Application scenario: When we need to create a lot of data in memory, we can think of using a generator to generate bit by bit (use a bit to produce a bit) to save memory overhead.

13.3 Built-in functions

Python provides us with many convenient built-in functions. Here we have compiled 36 for everyone to explain.

  • Group 1 (5 pieces)

    • abs, absolute value

      v = abs(-10)
    • pow, index

      v1 = pow(2,5) # 2 to the 5th power 2**5
      print(v1)
    • sum, sum

      v1 = sum([-11, 22, 33, 44, 55]) # Can be iterated - for loop
      print(v1)
    • divmod, find quotient and remainder

      v1, v2 = divmod(9, 2)
      print(v1, v2)
    • round, n decimal places (rounded)

      v1 = round(4.11786, 2)
      print(v1) # 4.12
  • Group 2: (4 pieces)

    • min, minimum value

      v1 = min(11, 2, 3, 4, 5, 56)
      print(v1) #2
      v2 = min([11, 22, 33, 44, 55]) # Type of iteration (for loop)
      print(v2)
      v3 = min([-11, 2, 33, 44, 55], key=lambda x: abs(x))
      print(v3) # 2
    • max, maximum value

      v1 = max(11, 2, 3, 4, 5, 56)
      print(v1)
      ?
      v2 = max([11, 22, 33, 44, 55])
      print(v2)
      v3 = max([-11, 22, 33, 44, 55], key=lambda x: x * 10)
      print(v3) # 55
    • all, whether all are True

      v1 = all( [11,22,44,""] ) # False
    • any, whether True exists

      v2 = any([11,22,44,""]) # True
  • Group 3 (3 pieces)

    • bin, decimal to binary

    • oct, decimal to octal

    • hex, decimal to hexadecimal

  • Group 4 (2 pieces)

    • ord, obtains the unicode code point corresponding to the character (decimal)

      v1 = ord("武")
      print(v1, hex(v1))
    • chr, get the corresponding character according to the code point (decimal)

      v1 = chr(27494)
      print(v1)
  • Group 5 (9 pieces)

    • int

    • foat

    • str, unicode encoding

    • bytes, utf-8, gbk encoding

      v1 = "Big Shaobing" # str type
      ?
      v2 = v1.encode('utf-8') # bytes type
      ?
      v3 = bytes(v1,encoding="utf-8") # bytes type
    • bool: Boolean type

    • list: list

    • dict: dictionary

    • tuple: tuple

    • set: collection

bool, list, tuple, dict, set, have been mentioned in the previous data types, click to jump to view

  • Group 6 (13)

    • len: length

    • print: output

    • input: input

    • open: open

    • type, get the data type

      v1 = "123"
      ?
      if type(v1) == str:
          pass
      else:
          pass
    • range

      for i in range(10):
          print(i)
      
      # Output: 0 1 2 3 4 5 6 7 8 9
    • enumerate

      v1 = ["Big Shaobing", "apple", 'root']
      ?
      for num, value in enumerate(v1, 1):
          print(num, value)
    • id: memory address

    • hash

      v1 = hash("Big Shaobing")
    • help, help information

      • pycharm, no need

      • terminal, use

    • zip

      v1 = [11, 22, 33, 44, 55, 66]
      v2 = [55, 66, 77, 88]
      v3 = [10, 20, 30, 40, 50]
          
      result = zip(v1, v2, v3)
      for item in result:
          print(item)
    • callable, whether it is executable, and whether parentheses can be added after it.

      v1 = "Big Shaobing"
      v2 = lambda x: x
      def v3():
          pass
      ?
      ?
      print( callable(v1) ) # False
      print(callable(v2))
      print(callable(v3))
    • sorted, sorted

      v1 = sorted([11,22,33,44,55])
      info = {
          "wupeiqi": {
              'id': 10,
              'age': 119
          },
          "root": {
              'id': 20,
              'age': 29
          },
          "seven": {
              'id': 9,
              'age': 9
          },
          "admin": {
              'id': 11,
              'age': 139
          },
      }
      ?
      result = sorted(info.items(), key=lambda x: x[1]['id'])
      print(result)
      data_list = [
          '1-5 Compiler and Interpreter.mp4',
          '1-17 Today's homework.mp4',
          '1-9 Python interpreter type.mp4',
          '1-16 Today's summary.mp4',
          '1-2 Creation of Class Notes.mp4',
          '1-15 Pycharm usage and cracking (win system).mp4',
          '1-12 python interpreter installation (mac system).mp4',
          '1-13 python interpreter installation (win system).mp4',
          '1-8 Introduction to Python.mp4', '1-7 Classification of programming languages.mp4',
          '1-3 Common basic computer concepts.mp4',
          '1-14 Pycharm usage and cracking (mac system).mp4',
          '1-10 CPython interpreter version.mp4',
          '1-1 Today's summary.mp4',
          '1-6 Three essential things to learn about programming.mp4',
          '1-18 homework answers and explanations.mp4',
          '1-4 programming language.mp4',
          '1-11 Environment setup instructions.mp4'
      ]
      result = sorted(data_list, key=lambda x: int(x.split(' ')[0].split("-")[-1]) )
      print(result)

13.4 Derivation

Derivation is a very convenient function provided in Python, which allows us to create lists, dicts, tuples, and sets and initialize some values through one line of code.

Please create a list and initialize it with: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9…299 integer elements.

data = []
for i in range(300):
    data.append(i)
  • list

    num_list = [ i for i in range(10)]
    ?
    num_list = [[i,i] for i in range(10)]
    ?
    num_list = [ [i,i] for i in range(10) if i > 6 ]
  • gather

    num_set = { i for i in range(10)}
    ?
    num_set = { (i,i,i) for i in range(10)}
    ?
    num_set = { (i,i,i) for i in range(10) if i>3}
  • dictionary

    num_dict = { i:i for i in range(10)}
    ?
    num_dict = { i:(i,11) for i in range(10)}
    ?
    num_dict = { i:(i,11) for i in range(10) if i>7}
  • Tuples, unlike other types.

    # The inner loop will not be executed immediately to generate data, but a generator will be obtained.
    data = (i for i in range(10))
    print(data)
    for item in data:
        print(item)

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python introductory skills treeBasic grammarCommonly used built-in functions 382,157 people are learning the system