Day17 函数的进阶
应用
- 赋值给变量
- 作函数参数
- 作函数返回值
def test():
return True
def test2(func): # 函数参数
var = func # 赋值给变量
return func # 函数返回值
if __name__ == '__main__':
t = test2(test())
print('t:', t)
t: True
内联函数
定义:接受函数作为输入和输出的函数。
“数据分析”中常用到高阶函数(map, reduce, filter, sorted, zip等)和匿名函数(lambda)
1.map()
定义:映射,将已有列表的元素通过函数映射到一个map类型的迭代器对象中,迭代器对象中的元素与已有列表的元素是一一对应的
from collections import Iterator
def f1(a):
return a.upper() # 将字符转换成大写
def map_main():
str1 = 'hello'
str2 = map(f1, str1)
print(type(str2)) # map()函数返回map类型对象
print(isinstance(str2, Iterator)) # 也是迭代器对象
print(list(str2))
print('*'*5 + 'next')
while True: # 迭代器只能使用一次,上面print(list(str2)执行后,下面便不能再使用该迭代器
try:
x = next(str2)
print(x, end='')
except StopIteration:
break
if __name__ == '__main__':
map_main()
<class ‘map’>
True
[‘H’, ‘E’, ‘L’, ‘L’, ‘O’]
*****next
2.reduce()
定义:映射,将列表中的元素依次代入函数进行迭代运算,返回的结果是一个计算后的数据,因此它传入的函数必须带两个参数
from functools import reduce
def f2(x, y):
return x * y
result1 = reduce(f2, range(1, 6)) # 计算阶乘
print('result1:', result1)
result2 = f2(f2(f2(f2(1, 2), 3), 4), 5)
print('result2:', result2)
result1: 120
result2: 120
3.filter()
定义:数据过滤
# filter: 数据过滤
from collections import Iterator
odd_numbers = filter(lambda x: x % 2 == 1, range(1, 20))
print(type(odd_numbers))
print(isinstance(odd_numbers, Iterator))
print(list(odd_numbers))
<class ‘filter’>
True
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
4.sorted()
定义:对可迭代对象排序。排序后的结构生成到一个新列表中。
# 默认排序
a = [3, 7, 4, 1, 9]
b = sorted(a) # 保留原列表
print('a:', a)
print('b:', b)
# 利用key排序,顺序
students = [('join', 'A', 15), ('frank', 'B', 23), ('dack', 'C', 20)]
s1 = sorted(students, key=lambda s: s[0])
print('s1:', s1)
# 降序
s2 = sorted(students, key=lambda s:s[0], reverse=True)
print('s2:', s2)
a: [3, 7, 4, 1, 9]
b: [1, 3, 4, 7, 9]
s1: [(‘dack’, ‘C’, 20), (‘frank’, ‘B’, 23), (‘join’, ‘A’, 15)]
s2: [(‘join’, ‘A’, 15), (‘frank’, ‘B’, 23), (‘dack’, ‘C’, 20)]
6.lambda
定义:lambda,匿名函数,一行的表达式,函数的复杂程度有限的时候。
# lambda
from functools import reduce
str2 = map(lambda a: a.upper(), 'hello')
print(list(str2))
result = reduce(lambda x, y: x * y, range(1, 6))
print(result)
[‘H’, ‘E’, ‘L’, ‘L’, ‘O’]
120
参数
字符串前加u, r, b
参考资料:urb
u:Unicode,一般用在中文
r:原生
b:bytes类型
1.位置、关键字、默认、可变
def print_hello(name, sex=1, *args, **kwargs): # 1.位置参数:name(0), sex(1) # 3.默认参数:sex=1 # 4.可变参数(*args, **kwags)
sex_dict = {1: u'男', 2: u'女'}
# print('hello %s %s, welcome to python world!' % (name, sex))
print('hello %s %s, welcome to python world!' % (name, sex_dict.get(sex)))
def print_hello_1(name, sex):
print(name, sex)
if __name__ == '__main__':
print_hello('tangu', 1)
print('*'*40 + '#')
print_hello('tangu', sex=2) # 2.关键字参数,sex=2
print('*'*40 + '解包裹参数') # 解包裹参数
args = ('jack', '男')
print_hello_1(*args) # 解元组(位置传递)
kargs = {'name': 'jack', 'sex': u'男'}
print_hello_1(**kargs) # 解字典(关键字传递)
hello tangu 男, welcome to python world!
****************************************#
hello tangu 女, welcome to python world!
****************************************解包裹参数
jack 男 jack 男
元信息
参考资料:参数元信息
作用:增强代码可读性
def add(x:int, y:int) -> int:
return x + y
help(add)
a = add(2, 3)
print('a:', a)
print(add.__annotations__) # 函数的注解只存储在__annotations__属性中
Help on function add in module main:
add(x:int, y:int) -> int
a: 5
{‘x’: <class ‘int’>, ‘y’: <class ‘int’>, ‘return’: <class ‘int’>}
内置函数
闭包和作用域
顺序:LEGB(Local->Embedded->Global->Built-in)
global
nonlocal