Python-Anonymous parameters and higher-order functions with actual parameters

1. Anonymous parameters

1. Anonymous function – a function without a name

Function name = lambda formal parameter list: return value
Equivalent to:
def function name (formal parameter list):
return return value
def sum2(num1, num2):
return num1 + num2
  
  
sum3 = lambda num1, num2: num1 + num2
  
print(sum2(100, 200))
print(sum3(100, 200))
  
# Exercise 1: Define an anonymous function to multiply a specified number by 100
big = lambda num: num * 100
print(big(30))
  
# Exercise 2: Define an anonymous function to determine whether the specified year is a leap year
is_leap_year = lambda year: year % 400 == 0 or year % 4 == 0 and year % 100 != 0
print(is_leap_year(2000))

2. Higher-order functions with actual parameters

1. Higher-order functions with actual parameters – functions whose parameters are functions

There are two ways to pass parameters to the parameters of the function corresponding to the actual parameter higher-order function:

a. Use the function name of an ordinary function that meets the requirements
b. Use anonymous functions that meet the requirements
# func1 is a higher-order function with actual parameters
def func1(x):
# x = t
x(10) + 10 #t(10)
  
  
def t(a):
print('hello world!')
return 100
  
  
func1(t)
  
func1(lambda b: 10)

3. Commonly used high-order functions with actual parameters

1. max, min, sorted, list.sort

1) Basic usage

max(container) – directly compares the size of the elements in the container to find the maximum value

2) Advanced usage

max(container, key=function) – Compare the sizes of elements according to the comparison rules set by the function to find the maximum value of the elements in the container
Function requirements: a. There is only one parameter, which represents each element in the container
b. There is a return value, and the return value is the comparison object
# Case 1: Find the largest element in nums
nums = [89, -345, 90, 34, 10]
print(max(nums))
  
#Case 2: Find the element with the largest absolute value in nums
nums = [89, -345, 90, 34, 10]
result = max(nums, key=lambda item: item ** 2)
print(result)
  
#Case 3: Find the element with the largest single digit in nums
nums = [88, -341, 90, 34, 10]
result = max(nums, key=lambda item: -item % 10 if item < 0 else item % 10)
print(result)
  
# Case 4: Find the information of the student with the highest score among students
students = [
{<!-- -->'name': 'Xiao Ming', 'age': 19, 'score': 98},
{<!-- -->'name': 'Zhang San', 'age': 20, 'score': 78},
{<!-- -->'name': '李思', 'age': 18, 'score': 99},
{<!-- -->'name': '王五', 'age': 22, 'score': 64}
]
result = max(students, key=lambda item: item['score'])
print(result)
  
# Exercise 1: Find the element with the smallest absolute value in nums
nums = [89, -345, 90, 34, 10]
result = min(nums, key=lambda item: item ** 2)
print(result)
  
# Exercise 2: Sort the elements in names according to the length of the names from largest to smallest
names = ['Jie', 'Tolsso', 'Obama', 'Mundo', 'Ice Shooter']
names.sort(key=lambda item: len(item), reverse=True)
print(names)
  
# Exercise 3: Sort middle school students by age from smallest to largest
students = [
{<!-- -->'name': 'Xiao Ming', 'age': 19, 'score': 98},
{<!-- -->'name': 'Zhang San', 'age': 20, 'score': 78},
{<!-- -->'name': '李思', 'age': 18, 'score': 99},
{<!-- -->'name': '王五', 'age': 22, 'score': 64}
]
new_students = sorted(students, key=lambda item: item['age'])
print(new_students)

2. map – Create a new container based on the elements in the original container

1) map (function, container) – Create a new container based on the elements in the container according to the rules set by the function

Function requirements: a. There is only one parameter, pointing to each element in the container
b. There is a return value, and the return value is the element in the new container

2) map(function, container 1, container 2) – Create a new container based on the elements in the container according to the rules set by the function

Function requirements: a. There are only 2 parameters, pointing to each element in the two containers
b. There is a return value, and the return value is the element in the new container

3) map(function, container 1, container 2, container 3,…) – Create a new container based on the elements in the container according to the rules set by the function

Note: If there are multiple containers behind the map, the number of elements in each container must be the same
# Case 1: Multiply all elements in nums by 10
nums = [89, -345, 90, 34, 10]
# [890, -3450, 900, 340, 100]
result = list(map(lambda item: item * 10, nums))
print(result)
  
#Case 2: Extract the single digits of all elements in nums
nums = [89, -345, 90, 34, 10]
# [9, 5, 0, 4, 0]
result = list(map(lambda item: item % 10 if item >= 0 else -item % 10, nums))
print(result)
  
# Case 3: Use the units digit of the element in nums1 as the tens digit of the element in the new container, and use the tens digit of the element in nums2 as the units digit of the element in the new container.
nums1 = [28, 682, 981, 83, 55, 79]
nums2 = [90, 27, 54, 81, 36, 75]
# [89, 22, 15, 38, 53, 97]
result = list(map(lambda i1, i2: i1 % 10 * 10 + i2 // 10 % 10, nums1, nums2))
print(result)
  
# Exercise 1: Use the map function to create a list corresponding to the passing scores in scores.
scores = [99, 80, 56, 70, 34, 55, 100, 23]
# Result: ['pass', 'pass', 'fail', 'pass', 'fail', 'fail', 'pass', \ 'failed']  
result = list(map(lambda item: 'failed' if item < 60 else 'passed', scores))
print(result)
  
# Exercise 2: Extract the surnames of all people in names (regardless of compound surnames)
names = ['Zhang San', 'Li Si', 'Zhao Liu', 'Wang Ming', 'Zhang Hong']
# Result: ['Zhang', 'Li', 'Zhao', 'Wang', 'Zhang']
result = list(map(lambda item: item[0], names))
print(result)
  
# Exercise 3: Create a students list based on the elements in the three lists of names, scores, and ages. The elements in the list are the dictionaries corresponding to each student. The keys of the dictionary are 'name', 'score' and 'age'names = ['Zhang San', 'Li Si', 'Zhao Liu', 'Wang Ming', 'Zhang Hong']
scores = [99, 80, 56, 70, 34]
ages = [22, 25, 19, 17, 23]
result = list(map(lambda i1, i2, i3: {<!-- -->'name': i1, 'score': i2, 'age': i3}, names, scores, ages))
print(result)

3. filter

filter(function, container) – Gets all elements of the container that meet the conditions specified by the function

Function requirements: a. There is only one parameter, pointing to each element in the container
b. There is a return value, and the return value is the condition that the element needs to be obtained
# Case 1: Delete scores below 60 points in scores (extract scores greater than or equal to 60 points)
scores = [99, 80, 56, 70, 34, 55, 100, 23]
result = list(filter(lambda item: item >= 60, scores))
print(result)

4. reduce – merge elements in a container

reduce(function, container, initial value) – Merge all elements in the container into one data according to the merging rules set by the function

Function requirements: a. There are only two parameters, the first parameter points to the initial value, and the second parameter points to each element in the container
b. There is a return value, and the return value is the merge rule
Note: reduce must be imported before using reduce
# Import reduce function
from functools import reduce
  
#Case 1: Find the sum of all elements in scores
scores = [99, 80, 56, 70, 34]
# 0 + 99 + 80 + 56 + 70 + 34
result = reduce(lambda i, item: i + item, scores, 0)
print(result) #339
  
#Case 2: Find the product of all elements in nums
nums = [10, 5, 8, 12, 40]
# 1 * 10 * 5 * 8 * 12 * 40
result = reduce(lambda i, item: i * item, nums, 1)
print(result)
  
#Case 3: Find the single-digit sum of all elements in scores
scores = [99, 80, 56, 70, 34]
# 0 + 99 + 80 + 56 + 70 + 34
result = reduce(lambda i, item: i + item % 10, scores, 0)
print(result)
  
#Case 4: Combine all elements in nums directly into one number
nums = [10, 5, 8, 12, 40]
# 10581240 -> '' + '10' + '5' + '8' + '12' + '40'
result = int(reduce(lambda i, item: i + str(item), nums, ''))
print(result)
  
# Case 5: Find the total scores of all students in students
students = [
{<!-- -->'name': 'Xiao Ming', 'age': 19, 'score': 98},
{<!-- -->'name': 'Zhang San', 'age': 20, 'score': 78},
{<!-- -->'name': '李思', 'age': 18, 'score': 99},
{<!-- -->'name': '王五', 'age': 22, 'score': 64}
]
# 0 + 98 + 78 + 99 + 64
result = reduce(lambda i, item: i + item['score'], students, 0)
print(result)