Skip to content

Commit e8e8d25

Browse files
committed
add 14_Day_Higher_order_functions Chinese support
1 parent 763e78b commit e8e8d25

File tree

1 file changed

+368
-0
lines changed

1 file changed

+368
-0
lines changed

Chinese/14_higher_order_functions.md

Lines changed: 368 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,368 @@
1+
<div align="center">
2+
<h1> 30天Python:第14天 - 高阶函数</h1>
3+
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
4+
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
5+
</a>
6+
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
7+
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
8+
</a>
9+
10+
<sub>作者:
11+
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
12+
<small>第二版:2021 年 7 月</small>
13+
</sub>
14+
15+
</div>
16+
17+
[<< 第 13 天](../13_Day_List_comprehension/13_list_comprehension.md) | [第 15 天>>](../15_Day_Python_type_errors/15_python_type_errors.md)
18+
19+
![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)
20+
21+
- [📘 第 14 天](#-第14天)
22+
- [高阶函数](#高阶函数)
23+
- [函数作为参数](#函数作为参数)
24+
- [函数作为返回值](#函数作为返回值)
25+
- [Python 闭包](#python闭包)
26+
- [Python 装饰器](#python装饰器)
27+
- [创建装饰器](#创建装饰器)
28+
- [将多个装饰器应用于单个函数](#将多个装饰器应用于单个函数)
29+
- [在装饰器函数中接受参数](#在装饰器函数中接受参数)
30+
- [内置高阶函数](#内置高阶函数)
31+
- [Python - Map 函数](#python---map函数)
32+
- [Python - Filter 函数](#python---filter函数)
33+
- [Python - Reduce 函数](#python---reduce函数)
34+
- [💻 练习:第 14 天](#-练习-第14天)
35+
- [练习:简单](#练习-简单)
36+
- [练习:中等](#练习-中等)
37+
- [练习:高级](#练习-高级)
38+
39+
# 📘 第 14 天
40+
41+
## 高阶函数
42+
43+
在 Python 中,函数被视为第一类公民,可以对函数执行以下操作:
44+
45+
- 一个函数可以接收一个或多个函数作为参数
46+
- 一个函数可以作为另一个函数的返回值
47+
- 一个函数可以被修改
48+
- 一个函数可以被赋值给变量
49+
50+
在本节中,我们将讨论:
51+
52+
1. 将函数作为参数传递
53+
2. 将函数作为返回值返回
54+
3. 使用 Python 闭包和装饰器
55+
56+
### 函数作为参数
57+
58+
```py
59+
def sum_numbers(nums): # 普通函数
60+
return sum(nums) # 使用内置函数sum的函数
61+
62+
def higher_order_function(f, lst): # 将函数作为参数
63+
summation = f(lst)
64+
return summation
65+
result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5])
66+
print(result) # 15
67+
```
68+
69+
### 函数作为返回值
70+
71+
```py
72+
def square(x): # 求平方函数
73+
return x ** 2
74+
75+
def cube(x): # 求立方函数
76+
return x ** 3
77+
78+
def absolute(x): # 求绝对值函数
79+
if x >= 0:
80+
return x
81+
else:
82+
return -(x)
83+
84+
def higher_order_function(type): # 返回一个函数的高阶函数
85+
if type == 'square':
86+
return square
87+
elif type == 'cube':
88+
return cube
89+
elif type == 'absolute':
90+
return absolute
91+
92+
result = higher_order_function('square')
93+
print(result(3)) # 9
94+
result = higher_order_function('cube')
95+
print(result(3)) # 27
96+
result = higher_order_function('absolute')
97+
print(result(-3)) # 3
98+
```
99+
100+
从上述示例中可以看到,高阶函数根据传入的参数来返回不同的函数。
101+
102+
## Python 闭包
103+
104+
Python 允许嵌套函数访问外部封闭函数的作用域。 这称为闭包。 让我们看看闭包在 Python 中的工作原理。在 Python 中,闭包是通过在另一个封装函数内部嵌套函数,然后返回内部函数来创建的。请看下面的例子。
105+
106+
**示例:**
107+
108+
```py
109+
def add_ten():
110+
ten = 10
111+
def add(num):
112+
return num + ten
113+
return add
114+
115+
closure_result = add_ten()
116+
print(closure_result(5)) # 15
117+
print(closure_result(10)) # 20
118+
```
119+
120+
## Python 装饰器
121+
122+
装饰器是一种设计模式,允许用户在不修改对象结构的情况下为其添加新功能。装饰器通常在你想要装饰的函数定义之前调用。
123+
124+
### 创建装饰器
125+
126+
要创建装饰器函数,我们需要一个带有内部包装器函数的外部函数。
127+
128+
**示例:**
129+
130+
```py
131+
# 普通函数
132+
def greeting():
133+
return 'Welcome to Python'
134+
def uppercase_decorator(function):
135+
def wrapper():
136+
func = function()
137+
make_uppercase = func.upper()
138+
return make_uppercase
139+
return wrapper
140+
g = uppercase_decorator(greeting)
141+
print(g()) # WELCOME TO PYTHON
142+
143+
# 使用装饰器实现上面的示例
144+
145+
'''这个装饰器函数是一个高阶函数,接收一个函数作为参数'''
146+
def uppercase_decorator(function):
147+
def wrapper():
148+
func = function()
149+
make_uppercase = func.upper()
150+
return make_uppercase
151+
return wrapper
152+
@uppercase_decorator
153+
def greeting():
154+
return 'Welcome to Python'
155+
print(greeting()) # WELCOME TO PYTHON
156+
```
157+
158+
### 将多个装饰器应用于单个函数
159+
160+
```py
161+
162+
'''这些装饰器函数是高阶函数,接收函数作为参数'''
163+
164+
# 第一个装饰器
165+
def uppercase_decorator(function):
166+
def wrapper():
167+
func = function()
168+
make_uppercase = func.upper()
169+
return make_uppercase
170+
return wrapper
171+
172+
# 第二个装饰器
173+
def split_string_decorator(function):
174+
def wrapper():
175+
func = function()
176+
splitted_string = func.split()
177+
return splitted_string
178+
179+
return wrapper
180+
181+
@split_string_decorator
182+
@uppercase_decorator # 在此情况下,装饰器的顺序很重要 - .upper()函数不适用于列表
183+
def greeting():
184+
return 'Welcome to Python'
185+
print(greeting()) # WELCOME TO PYTHON
186+
```
187+
188+
### 在装饰器函数中接受参数
189+
190+
大多数时候我们需要我们的函数接受参数,所以我们可能需要定义一个接受参数的装饰器。
191+
192+
```py
193+
def decorator_with_parameters(function):
194+
def wrapper_accepting_parameters(para1, para2, para3):
195+
function(para1, para2, para3)
196+
print("I live in {}".format(para3))
197+
return wrapper_accepting_parameters
198+
199+
@decorator_with_parameters
200+
def print_full_name(first_name, last_name, country):
201+
print("I am {} {}. I love to teach.".format(
202+
first_name, last_name, country))
203+
204+
print_full_name("Asabeneh", "Yetayeh",'Finland')
205+
```
206+
207+
## 内置高阶函数
208+
209+
在本部分中,我们将讨论一些内置的高阶函数,如*map()*, *filter**reduce*
210+
Lambda 函数可以作为参数传递,其最佳使用案例是在地图、过滤和减少等功能中。
211+
212+
### Python - Map 函数
213+
214+
map()函数是一个内置函数,接收一个函数和可迭代对象作为参数。
215+
216+
```py
217+
# 语法
218+
map(function, iterable)
219+
```
220+
221+
**示例:1**
222+
223+
```py
224+
numbers = [1, 2, 3, 4, 5] # 可迭代对象
225+
def square(x):
226+
return x ** 2
227+
numbers_squared = map(square, numbers)
228+
print(list(numbers_squared)) # [1, 4, 9, 16, 25]
229+
# 让我们应用lambda函数
230+
numbers_squared = map(lambda x : x ** 2, numbers)
231+
print(list(numbers_squared)) # [1, 4, 9, 16, 25]
232+
```
233+
234+
**示例:2**
235+
236+
```py
237+
numbers_str = ['1', '2', '3', '4', '5'] # 可迭代对象
238+
numbers_int = map(int, numbers_str)
239+
print(list(numbers_int)) # [1, 2, 3, 4, 5]
240+
```
241+
242+
**示例:3**
243+
244+
```py
245+
names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # 可迭代对象
246+
247+
def change_to_upper(name):
248+
return name.upper()
249+
250+
names_upper_cased = map(change_to_upper, names)
251+
print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
252+
253+
# 让我们应用lambda函数
254+
names_upper_cased = map(lambda name: name.upper(), names)
255+
print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
256+
```
257+
258+
map 函数实际上是迭代列表。例如,它将名称更改为大写并返回一个新列表。
259+
260+
### Python - Filter 函数
261+
262+
filter()函数调用指定函数,该函数对指定的可迭代对象(列表)中的每个项目返回布尔值。它过滤出满足过滤条件的项目。
263+
264+
```py
265+
# 语法
266+
filter(function, iterable)
267+
```
268+
269+
**示例:1**
270+
271+
```py
272+
# 让我们只过滤偶数
273+
numbers = [1, 2, 3, 4, 5] # 可迭代对象
274+
275+
def is_even(num):
276+
if num % 2 == 0:
277+
return True
278+
return False
279+
280+
even_numbers = filter(is_even, numbers)
281+
print(list(even_numbers)) # [2, 4]
282+
```
283+
284+
**示例:2**
285+
286+
```py
287+
numbers = [1, 2, 3, 4, 5] # 可迭代对象
288+
289+
def is_odd(num):
290+
if num % 2 != 0:
291+
return True
292+
return False
293+
294+
odd_numbers = filter(is_odd, numbers)
295+
print(list(odd_numbers)) # [1, 3, 5]
296+
```
297+
298+
```py
299+
# 过滤长名称
300+
names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # 可迭代对象
301+
def is_name_long(name):
302+
if len(name) > 7:
303+
return True
304+
return False
305+
306+
long_names = filter(is_name_long, names)
307+
print(list(long_names)) # ['Asabeneh']
308+
```
309+
310+
### Python - Reduce 函数
311+
312+
*reduce()*函数定义在 functools 模块中,我们需要从这个模块中导入它。像 map 和 filter 一样,它接收两个参数,一个函数和一个可迭代对象。然而,它不返回另一个可迭代对象,而是返回一个单一的值。
313+
**示例:1**
314+
315+
```py
316+
numbers_str = ['1', '2', '3', '4', '5'] # 可迭代对象
317+
def add_two_nums(x, y):
318+
return int(x) + int(y)
319+
320+
total = reduce(add_two_nums, numbers_str)
321+
print(total) # 15
322+
```
323+
324+
## 💻 练习:第 14 天
325+
326+
```py
327+
countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
328+
names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham']
329+
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
330+
```
331+
332+
### 练习:简单
333+
334+
1. 解释 map、filter 和 reduce 的区别。
335+
2. 解释高阶函数、闭包和装饰器的区别。
336+
3. 定义调用函数,见示例。
337+
4. 使用 for 循环打印 countries 列表中的每个国家。
338+
5. 使用 for 循环打印 names 列表中的每个名称。
339+
6. 使用 for 循环打印 numbers 列表中的每个数字。
340+
341+
### 练习:中等
342+
343+
1. 使用 map 将 countries 列表中的每个国家更改为大写,生成一个新列表。
344+
2. 使用 map 将 numbers 列表中的每个数字更改为平方,生成一个新列表。
345+
3. 使用 map 将 names 列表中的每个名称更改为大写,生成一个新列表。
346+
4. 使用 filter 过滤出包含“land”的国家。
347+
5. 使用 filter 过滤出正好六个字符的国家。
348+
6. 使用 filter 过滤出包含六个字母及以上的国家。
349+
7. 使用 filter 过滤出以'E'开头的国家。
350+
8. 链接两个或多个列表迭代器(例如 arr.map(callback).filter(callback).reduce(callback))。
351+
9. 声明一个函数 get_string_lists,它接收一个列表作为参数并返回一个仅包含字符串项的列表。
352+
10. 使用 reduce 对 numbers 列表中的所有数字求和。
353+
11. 使用 reduce 将所有国家连接起来,生成句子:Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries。
354+
12. 声明一个函数 categorize_countries,返回一个包含某种通用模式的国家列表(可以在本仓库的 countries.js 文件中找到国家列表,例如 'land', 'ia', 'island', 'stan')。
355+
13. 创建一个返回字典的函数,其中键表示国家名称的首字母,值表示以该字母开头的国家数。
356+
14. 声明一个 get_first_ten_countries 函数 - 它返回数据文件夹中 countries.js 列表中的前十个国家。
357+
15. 声明一个 get_last_ten_countries 函数 - 它返回国家列表中的最后十个国家。
358+
359+
### 练习:高级
360+
361+
1. 使用 countries_data.py (https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) 文件,完成以下任务:
362+
- 按国家名称、首都和人口排序国家
363+
- 按位置排序出前十个最常用语言。
364+
- 排序出前十个人口最多的国家。
365+
366+
🎉 恭喜你! 🎉
367+
368+
[<< 第 13 天](../13_Day_List_comprehension/13_list_comprehension.md) | [第 15 天>>](../15_Day_Python_type_errors/15_python_type_errors.md)

0 commit comments

Comments
 (0)