函数进阶
01review复习
1.什么是函数
本质:就是实现某一个功能的代码
2.分类
系统函数:自定义函数;
print,input,type
自定义函数
3.创建函数
def 函数名(形参1,形参2,。。。)
说明文档
“”“
”“‘
函数体
4.调用函数
函数名(实参1,实参2,。。。)
5。返回值
1) 确定返回值
return 返回值
2) 获取返回值
获取函数调用表达式的值
3)什么时候需要返回值
需要return的时候
6.return
7.参数
def func1(x, y, z):
pass
func1(10, 20, 30)
x = 23 # type:intxxxxxxxxxx def func1(x, y, z): passdef func1(x, y, z): passfunc1(10, 20, 30)x = 23 # type:int
# 2. 写程序实现split的功能,将字符串中指定子串作为切割点对字符串进行切割
# 'how are you? and you?' 'you'
def split(str1: str, point: str, n=0):
"""
字符串切割
:param str1: 原字符串
:param point: 切割点
:param n: 切割次数,如果是0标签全切
:return: 切完后的数据
"""
result = []
new_str = ''
index = 0
len1 = len(str1)
len2 = len(point)
count = 0
while True:
if str1[index: index + len2] == point:
result.append(new_str)
new_str = ''
index += len2
count += 1
# 控制切割次数
if count == n:
result.append(str1[index:])
break
else:
new_str += str1[index]
index += 1
if index >= len1:
result.append(new_str)
break
return result
message = 'youhow are youyou? and you?you'
print(split(message, 'you', 2))
def exchange_key_value(dict1: dict):
return {value: key for key, valuein dict1.items()} # 获取字典.items()
def replace(str1: str, old: str, new: str):
new_str = ''
index = 0
len1 = len(str1)
len2 = len(old)
while True:
if str1[index: index + len2] == old:
new_str += new
index += len2
else:
new_str += str1[index]
index += 1
if index >= len1:
break
return new_str
message = 'how are you? and you?'
old = 'you'
print(replace(message, old, 'me'))
# 3. 编写一个函数,交换指定字典的key和value。
def exchange_key_value(dict1: dict):
return {value: key for key, value in dict1.items()}
print(exchange_key_value({'a': 10, 'b': 20}))
# 4. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
def get_letter(str1: str):
return ''.join(x for x in str1 if x.isupper() or x.islower())
print(get_letter('shs函数式2234ksMNs'))
# 5.写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
def capitalize(str1: str):
first_char = str1[0]
if first_char.islower():
return first_char.upper() + str1[1:]
return str1
# 6. 写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
def endswith(str1: str, end: str):
return str1[-len(end):] == end
# 7. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
def isdigit(str1: str):
for x in str1:
if not '0' <= x <= '9':
return False
return True
# 8.写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
def upper(str1: str):
new_str1 = ''
for x in str1:
if 'a' <= x <= 'z':
new_str1 += chr(ord(x) - 32)
else:
new_str1 += x
return new_str1
print(upper(message))
# 9.写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
def rjust(str1: str, width: int, char: str):
len1 = len(str1)
if width <= len1:
return str1
return (width - len1) * char + str1
# 10. 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
def index(list1: list, item):
result = []
for index, x in enumerate(list1):
if x == item:
result.append(index)
if result:
return ','.join([str(x) for x in result])
else:
return -1
print(index([1, 2, 45, 'abc', 1, '你好', 1, 0], 100))
# 11.写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
def max1(seq):
if type(seq) == dict:
new_seq = list(seq.values())
else:
new_seq = list(seq)
t = new_seq[0]
for x in new_seq[1:]:
if x > t:
t = x
return t
# 12.定义一个自己的update函数,将一个字典中所有的键值对添加到另外一个字典中
def update(dict1: dict, dict2: dict):
for key in dict2:
dict1[key] = dict2[key]
03匿名函数
# 1. 匿名函数 - 没有名字的函数
语法:
函数名 = lambda 形参列表:返回值
相当于
def 函数名(形参列表):
return 返回值
# 2.注意: 匿名函数的本质还是函数;普通函数中的绝大部分内容匿名函数都支持
# 练习:求任意两个数据的和的匿名函数
# def sum1(num1: int, num2=2):
# return num1 + num2
x = lambda num1, num2=2: num1 + num2
print(x(10, 20))
print(x(num1=100, num2=200))
print(x(100))
# 练习1: 写一个匿名函数判断指定的年是否是闰年
is_leap_year = lambda year: (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(is_leap_year(2001))
# 练习:求值最大的元素
nums = [12, 39, 18, 80, 34]
print(max(nums))
# # 练习:求个位数最大的元素
def func1(x):
return x % 10
print(max(nums, key=func1))
print(max(nums, key=lambda x: x % 10))
# 练习:求绝对值最大的元素
nums = [12, 39, -18, -80, 34]
print(max(nums, key=lambda x: x**2))
print(max(nums, key=lambda x: -x if x < 0 else x))
1变量作用域 - 变量使用范围
根据变量作用域不同,可以将变量分为两种,全局变量,局部变量
2全局变量
定义在函数或者类外面的变量就是全局变量(没有定义在函数里面和类里面的变量就是全局变量);
全局变量的作用域,从定义开始到程序结束
# a是全局变量
a = 10
print('外面a:', a)
# b是全局变量
# b是全局变量
for b in range(3):
# c是全局变量
c = 20
print('循环里面a:', a)
print('循环里面b:', b)
print('外面b:', b)
print('外面c:', c)
def func1():
print('函数里面a:', a)
print('函数里面b:', b)
print('函数里面c:', c)
3.局部变量
定义在函数里面的变量就是局部变量。(形参也是局部变量)
局部变量的作用域,从定义开始到函数结束
# d、e和f都是局部变量
def func1(d, e):
f = 100
print('函数里面:', d, e, f)
func1(300, 400)
# print('函数外面:', d)
# print('函数外面:', f)
4.global关键字
变量能不能使用,看的是使用的时候内存中有没有
定义全局变量的时候,全局变量保存在全局栈区间,程序结束后才会被自动释放;
局部变量是保存在函数对应的临时栈区间中,函数调用结束后就会被自动释放。
global是函数体中关键字,可以在函数中修饰变量,让变量在使用和保存的时候在全局栈区间进行。
1) 函数中修改全局变量的值
2) 直接在函数体定义全局变量
print('------------------------------------华丽的分割线-----------------------------------')
aa = 100
bb = 100
def func2():
# 不会修改全局变量aa的值,而且创建一个局部变量aa
aa = 200
print('里面aa:', aa) # 在函数里面使用的是局部变量aa的值
# print(bb) # 报错! global修改变量必须放在这个变量使用之前
global bb
bb = 200
print('里面bb:', bb)
global cc
cc = 300
func2()
print('外面aa:', aa) # 在函数外面使用的是全局变量aa的值
print('外面bb:', bb)
print('外面cc:', cc)
高阶函数
1.函数就是变量
python中定义函数其实就是定义一个类型是function的变量,函数名就是变量名
变量能做的事情函数都可以做。
def sum2(num1, num2):
return num1 + num2
# sum2 = lambda num1, num2: num1 + num2
b = [10, 20, 30]
print(type(b), type(sum2)) # <class 'list'> <class 'function'>
print(b[0], sum2(1, 3))
c = b
d = sum2
print(c[0], d(10, 20))
list1 = [10, b, sum2]
print(list1[1][-1]) # b[-1] -> [10, 20, 30][-1] -> 30
print(list1[-1](10, 20)) # sum2(10, 20) -> 30
# 2. 高阶函数 - 实参高阶函数、返回值高阶函数
# 1)实参高阶函数 - 函数的参数是函数
# 应该怎么来确定函数的参数是什么? - 看函数体中这个参数怎么用的
def func1(x):
print(x(10, 20)[-1])
def temp(a, b):
return 'abc'
func1(temp)
# 2) 返回值高阶函数 - 函数的返回值是函数
def func2():
def temp(x):
return 23
return temp
print(func2()(7) + 20)
# 装饰器 - 既是实参高阶函数,又是返回值高阶函数, 还得自己写!
06常用的实参高阶函数
-
max min sorted sort - 参数 key要求事一个函数
max(序列,key = 函数) - 按照函数指定的比较规则来获取序列中最大的元素
函数的要求:1)参数 - 有且只有一个参数,这个参数代表前面序列中的每个元素
2)返回值 - 有一个返回值;返回值就是比较对象。
注意:如果一个函数的参数是函数,这个参数有两种传值方式:
a.普通函数的函数名
b.匿名函数的函数名
nums = [10, 29, 87, 34, -231, 72]
# 练习1:求元素最大值
print(max(nums)) # 87
# 练习2:求元素最大值
result = max(nums, key=lambda item: item)
print(result) # 87
# 练习3:求个位数元素最大值
result = max(nums, key=lambda item: item % 10)
print(result) # 29
# 练习4:求绝对值最小的元素
result = min(nums, key=lambda item: item ** 2)
print(result)
# 练习5:求nums中数值最大的元素: '1998'
nums = ['235', '90', '71', '1998', '80']
result = max(nums, key=lambda item: int(item))
print(result) # '1998'
# 练习6:将nums中的元素按照十位数的大小从小到大排序
nums = [913, 281, 1765, 92, 802] # [802, 913, 1765, 281, 92]
new_nums = sorted(nums, key=lambda item: item // 10 % 10)
print(new_nums) # [802, 913, 1765, 281, 92]
# 练习7:获取nums中各个位数之和最小的元素
nums = [1002, 908, 99, 76, 502] # [3, 17, 18, 13, 7] -> 1002
# 方法一:
def temp(item):
s = 0
for x in str(item):
s += int(x)
return s
result = min(nums, key=temp)
print(result)
# 方法二
# 1002 - > '1+0+0+2' -> '+'.join('1002') -> '1+0+0+2'
result = min(nums, key=lambda item: eval('+'.join(str(item))))
print(result)
2.map - 映射
1)map(函数,序列) - 按照函数制定的规则将原序列转换成新的序列列表,返回值是map对象-本质是徐磊
函数要求:a.参数:有且只有1个参数;参数代表后面的这个序列中的元素
b.返回值:有一个返回值,返回值就是新序列中的元素
2)map(函数, 序列1, 序列2)
函数要求:a.参数:有且只有2个参数, 分别代码后面两个序列中的元素
b.返回值:有一个返回值;返回值就是新序列中的元素
3)map(函数, 序列1, 序列2, 序列3)
函数要求:a.参数:有且只有3个参数;分别代码后面3个序列中的元素
b.返回值:有一个返回值;返回值就是新序列中的元素
map(函数, 序列1, 序列2, 序列3,...)
# 获取nums中所有元素的个位数
nums = [128, 239, 87, 96, 102, 91]
# [8, 9, 7, 6, 2, 1]
result = list(map(lambda item: item % 10, nums))
print(result) # [8, 9, 7, 6, 2, 1]
str1 = 'abcde'
nums = [10, 20, 30, 40, 50]
# -> ['a10', 'b20', 'c30', 'd40', 'e50']
result = list(map(lambda i1, i2: i1 + str(i2), str1, nums))
print(result) # ['a10', 'b20', 'c30', 'd40', 'e50']
# 3. reduce
# 注意:reduce在使用之前必须先导入
reduce(函数,序列,初始值)
- 按照函数指定的规则将所有元素合并成一个数据
- 返回值:有一个返回值:秒速初始值和元素之间的合并方式
ums = [10, 30, 20] # 所有元素的和:60
# 0 + 10 + 30 + 20 -> i + item
result = reduce(lambda i, item: i+item, nums, 0)
print(result) # 60
nums = [10, 40, 20] # 所有元素的乘积:8000
# 1 * 10 * 40 * 20 -> i * item
result = reduce(lambda i, item: i * item, nums, 1)
print(result) # 8000
nums = [12, 34, 91] # 所有元素个位数的和:7
# 0 + 2 + 4 + 1 -> 0 + 12%10 + 34%10 + 91%10 -> i + item%10
result = reduce(lambda i, item: i + item % 10, nums, 0)
print(result) # 7
nums = [10, 40, 20] # '104020'
# '' + '10' + '40' + '20' -> '' + str(10) + str(40) + str(20) -> i + str(item)
result = reduce(lambda i, item: i + str(item), nums, '')
print(result) # '104020'
# 求所有数字的和
list1 = [10, 'abc', '2.4', 'hans', 5.5, 3] # 18.5
# [10, 5.5, 3]
# 方法1:
result = reduce(lambda i, item: i + item, [x for x in list1 if type(x) in (int, float)], 0)
print(result)
# 方法2:
# list1 = [10, 'abc', '2.4', 'hans', 5.5, 3]
# 0 + 10 + 5.5 + 3 -> 0 + 10 + 0 + 0 + 0 + 5.5 + 3 -> i + item / i + 0
result = reduce(lambda i, item: i+item if type(item) in (int, float) else i+0, list1, 0)
print(result)
# 将所有偶数的十位数和奇数的个位数求和
# 将所有偶数的十位数和奇数的个位数求和
nums = [23, 54, 801, 132, 92] # 3+5+1+3+9
# i + item % 10 、 i + item // 10 % 10
def temp(i, item):
if item % 2:
return i + item % 10
return i + item // 10 % 10
# result = reduce(lambda i, item: i + item % 10 if item % 2 else i + item // 10 % 10, nums, 0)
result = reduce(temp, nums, 0)
print(result)
本文深入探讨Python的函数进阶,包括匿名函数lambda的使用,理解函数作为变量的概念,以及讲解了高阶函数如max、min、sorted等如何使用函数作为参数。同时介绍了如何在函数中修改全局变量以及map和reduce函数的应用。

386

被折叠的 条评论
为什么被折叠?



