python--function advanced

1. Variable variable scope

  1. According to the different scope of variables, variables can be divided into global variables and local variables

  2. Global variables: Variables that are not defined in functions or classes in Python are global variables by default.

    The scope of global variables is from the beginning of the definition to the end of the program

  3. Local variables: Variables defined in functions in Python are local variables.

    Local variables are scoped from the beginning of the definition to the end of the function

  4. Global variables are saved in the global stack area by default, and the global variables will be released automatically after the end of the program

    When calling a function, the system will automatically create a temporary stack area for this function to save the data (local variables) generated in the function. The temporary stack area corresponding to the function will be released automatically when the function call ends.

  5. In the function, the keyword global can be used to modify the saving method of local variables

    # The global variable name is placed before the definition variable statement
    def func(a):
        global b
        b = 20
    # The variable b can be used globally
    # You can use the global keyword to modify the value of a global variable inside a function
    name = 'xiaoming'
    def func(a):
        global name 	#If you do not add the global keyword + variable name, another local variable value will be created.
        name = 'xiaohua'

2. Anonymous function lambda

  1. A lambda function is also called an anonymous function, that is, the function does not have a specific name.

    # function name = lambda parameter list: return value
    # normal function
    def f(x):
      	return x**2
    print f(4)
    # anonymous function
    g = lambda x : x**2
    print g(4)
  2. The parameter usage is the same as that of a normal function, but the formal parameter data type cannot be defined (but the type specification can be performed by defining a default value)

3. Higher-order functions with actual parameters

  1. Function parameters are functions Functions are arguments Higher-order functions

  2. max() min() sorted() list.sort

    num_list = [1, 23, 34, 45, -4600, 52, 52, 127, 536]
    # Take the maximum value according to the size of the single digit
    print(max(num_list, key=lambda num: num % 10))
    # Take the maximum value according to the absolute value
    print(max(num_list, key=lambda num: num **2))
    # Exercise 1: Find the longest string in list1
    list1 = ['Hello', 'hello', 'how are you', 'thank you! and you?', 'study hard, improve every day']
    print(max(list1, key=lambda item: len(item)))
    # Exercise 2: Find the smallest ten-digit element in nums
    nums = [92, 129, 37, 99, 150, 501]
    print(min(nums, key=lambda item: item // 10 % 10))
    # Find the largest sum of the digits in nums
    # method 1
    print(max(nums, key=lambda item: sum([int(x) for x in str(item)])))
    # Method 2
    print(max(nums, key=lambda item: eval('+'.join(str(item)))))
    # Method 3
    def sum_num(item):
        sum1 = 0
        for x in str(item):
        return sum1
    # Exercise 3: Sort all students according to age value from small to large
    students = [
        {'name': 'stu1', 'age': 18, 'score': 90},
        {'name': 'stu2', 'age': 22, 'score': 98},
        {'name': 'stu3', 'age': 25, 'score': 78},
        {'name': 'stu4', 'age': 19, 'score': 81},
        {'name': 'stu5', 'age': 20, 'score': 92}
    print(sorted(students, key=lambda item: item['age']))
  3. map creates a new sequence based on the elements in the original sequence, the original sequence can be one or more

    map( function, sequence)

    1. Function requirements: There are and only (number of sequences) parameters (representing each element in the following sequence)
    2. There is a return value, the return value is the element in the new sequence (the return result is an iterator)
    # The map( function, sequence) function has one argument
    # map( function, sequence1, sequence2) function has two parameters
    num1 = [1, 2, 3, 33, 23, 54]
    num2 = [1, 23, 67, 54, 345, 87]
    # Each element in num1 is multiplied by 10
    print(list(map(lambda x:x*10,num1)))
    # The result is [10, 20, 30, 330, 230, 540]
    # Multiply the elements at the corresponding positions in num1 num2
    print(list(map(lambda x,y:x*y,num1,num2)))
    # The result is [1, 46, 201, 1782, 7935, 4698]
    # Exercise 1: Get the last name of each person in names
    names = ['He Xiaodong', 'Zhang San', 'Li Si', 'Wang Wu', 'Wang Er', 'Zhao Liu']
    print(list(map(lambda name: name[0], names)))
    # Exercise 2:
    students = [
        {'name': 'stu1', 'age': 18, 'score': 90},
        {'name': 'stu2', 'age': 22, 'score': 98},
        {'name': 'stu3', 'age': 25, 'score': 78},
        {'name': 'stu4', 'age': 19, 'score': 81},
        {'name': 'stu5', 'age': 20, 'score': 92}
    subjects = ['digital information', 'Financial Mathematics', 'garden design', 'economy', 'computer software']
    # ['Electronic information-stu1', 'Financial mathematics-stu2',....]
    print(list(map(lambda sub, stu: f'{sub}-{stu["name"]}', subjects, students)))
  4. reduce combines the elements in the sequence into one data

    reduce( function, sequence, initial value) combines the elements in the sequence into one data according to the rules specified by the function

    1. Function requirements:
      1. There are only two parameters (the first parameter points to the initial value, and the second parameter represents each element in the sequence
      2. only need a return value
    2. Initial value:
      1. Cumulative evaluation value and initial value are 0
      2. Cumulatively calculate the product of values, the initial value is 1
      3. Merge strings, the initial value is an empty string
    # reduce( function, sequence, initial value) combines the elements in the sequence into one data according to the rules specified by the function
    result1 = reduce(lambda x, item: x + item, nums, 0)
    # The result is 520
    result2 = reduce(lambda x, item: x + item % 10, nums, 0)
    # The result is 10
    result3 = reduce(lambda x, item: (x + str(item)), nums, '')
    # The result is 123014055112

4. Iterator iter

  1. concept

    1. The iterator is a container data type (it can be traversed or converted into a list). It cannot directly provide an iterator, and can only convert other sequences into iterators.

    2. Features:

      1. When printing an iterator, you cannot see which elements are in the iterator.
    3. Unable to get the number of elements in the iterator through len

      1. If you want to use the elements in the iterator, you must take the elements out of the iterator, and the taken elements will disappear forever in the iterator
    4. Any data can be used as an element in an iterator

  2. Manipulating iterators

    1. create iterator

      l1 = iter('abc')
    2. print iterator cannot view element

      # The result is <str_iterator object at 0x7fa52ec4f760>
  3. Manipulate the elements in the iterator

    1. No matter how to get an element in the iterator, the element will disappear from the iterator

    2. get a single element

      next( iterator) Get the frontmost element of the iterator, and it will disappear if it is taken away

      i3 = iter([1, 2, 3, 4, 5, 52, 1, 4, 1])
      #	1
      #	2
      #	3
      # [4, 5, 52, 1, 4, 1]
      # An error is reported because the above has become an empty iterator
    3. traverse

      for variable in iterator:

      ​ loop body

      The iterator is empty after traversal

      for x in i3:
  4. shuffle

Tags: Python programming language

Posted by Nothsa on Wed, 22 Mar 2023 09:08:01 +0530