1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# def 定义函数
def add(x, y):
print("x is {} and y is {}.".format(x, y))
return x + y
add(5, 6)
add(y = 6, x = 5) # 关键词参数可为任意顺序
# 可变参数函数
def varargs(*args): # * 展开元组
return args
varargs(1, 2, 3) # => (1, 2, 3)
def keyword_args(**kwargs): # ** 展开字典
return kwargs
keyword_args(big = 1, small = 0) # => {"big": 1, "small": 0}
def all_args(*args, **kwargs): # 混用参数
print(args, end = ", ")
print(kwargs)
args = (1, 2, 3, 4)
kwargs = {"a": 1, "b": 2, "c": 3}
all_args(*args) # => (1, 2, 3, 4), {}
all_args(**kwargs) # => (), {"a": 1, "b": 2, "c": 3}
all_args(*args,**kwargs) # => (1, 2, 3, 4), {"a": 1, "b": 2, "c": 3}
# 返回元组
def swap(x, y):
return y, x
x, y = 1, 2
x, y = swap(x, y) # => x = 2, y = 1
# 函数作用域
x = 5
def set_x(num):
x = num
def set_global_x(num):
global x
x = num
set_x(0)
print(x) # => 5
set_global_x(1)
print(x) # => 1
# 函数是 "一等公民"
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
# 匿名函数
func1 = lambda x: x > 2
func2 = lambda x, y: x ** 2 + y ** 2
func1(3) # => True
func2(2, 1) # => 5
# 高阶函数: map 映射, filter 过滤
list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
# 推导式: 列表, 字典, 集合
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
|