其他分享
首页 > 其他分享> > 匿名函数 生成式 匿名函数内置函数

匿名函数 生成式 匿名函数内置函数

作者:互联网

目录

作业讲解

# 1.有参函数多种用户认证方式
data_list = ['jason|123','kevin|321','oscar|222']


def login_auth(condition):
    def outer(func_name):
        def inner(*args,*kwargs):
            username = input('username>>>:').strip()
            password = input('password>>>:').strip()
            if condition == 'absolute':
                if username == 'jason' and password =='123':
                    res = func_name(*args,**kwargs)
                    return res
                else:
                    print('不允许执行')
             elif condition == 'list_type':
                for user_data in data_list:
                    real_name,real_pwd = user_data.split('|')
                    if real_name == username and real_pwd == password:
                        res = func_name(*args,**kwargs)
                        return res
             elif condition == 'file_type':
                with open(r'userinfo.txt','r',encoding='uyf8') as f:
                    for line in f:
                        real_name,real_pwd = line.split('|')
                        if real_name == username and password == real_pwd_n.strip('|'):
                            res = func_name(*args,**kwargs)
                            return res
    return inner
return outer

@login_auth('absolute')
def func1():
    print('from func1')
    return 1
@login_auth('list_type')
def func2():
    print('from func2')
    return 2
@login_auth('file_type')
def func3():
    print('from func3')
    return 3


func1()
func2()
func3()
# 2.递推回溯求解某个人的年龄
def get_age(n):
    if n == 1:
        return 18
    return get_age(n-1) + 2
res = get_age(5)
print(res)

三元表达式

作用:

	减少代码行数

应用:

	仅限于二选一的情况并且不建议嵌套使用
'''雏形'''
1.获取用户输入的用户名 如果是jason就打印欢迎,否则打印滚蛋
username = input('username>>>:').strip()
if username == 'jason':print('欢迎')
else: print('滚蛋')

2.编写一个函数 比较两个数的大小 返回较大的那个
def my_max(a,b):
    return a if a>b else b
'''
等同于:
	if a>b:
		return a
	else:
		return b
'''
res = my_max(1,10)
print(res)

结构:

		值1	 if 	条件	 else 	值2

		如果条件成立,使用 if 前面的值

		如果条件不成立,使用 if 后面的值
print('哈哈' if 0 else '嘿嘿')	# 嘿嘿
print('嚯嚯' if 1 else '哼哼')	# 嚯嚯
1.获取用户输入的用户名 如果是jason就打印欢迎,否则打印滚蛋
username = input('username>>>:').strip()
if username == 'jason':print('欢迎')
else:print('滚蛋')

'''在python中代码不是越精简越好,精简过程中要保证代码的可读性'''

各种生成式

1.列表生成式

​ 列表生成式中只能出现 for 和 if

#给列表里的所有数据值加上_NB后缀
name_list = ['jason','kevin','oscar','jerry','tony']
#思考过程:
1.定义一个新的列表
new_list = []
2.循环原列表中的所有数据值
for name in name_list:
3.拼接_NB后缀
new_name = name + '_NB'
4.追加到新的列表中
new_list.append(new_name)
print(new_list)

'''运用列表生成式-->一行代码解决'''
new_list = [name + '_NB' for name in name_list]
# 先执行for循环,然后将一个个的数据值交给for循环前面的代码处理
print(new_list)
# 支持if判断,先执行for循环,然后将一个个数据值交给if判断,最后进行for循环前面处理
new_list = [name + '_NB' for name in name_list if name != 'jason']
print(new_list)


2.字典生成式

new_dict = {i:'jason' for i in range(10) if i==6}
print(new_dict)

3.集合生成式

new_set = {i for i in range(18)}
print(set(new_set))
new_set2 = {a for a in range(18) if a == 8 or a == 6}
print(set(new_set2))

匿名函数

定义:没有函数名的函数

语法结构:

lambda 形参(可以没有、一个、多个):返回值(返回表达式运行后的结果)
# 构建的是一个函数对象,需要用一个变量名去接收返回值

案例:

(lambda x: x+1)(123) # 直接调用
res = lambda x:x+1 # 命名调用
print(res(123))

res1 = (lambda x: x + 1)(5)
print('res1=', res1)

# 如果x大于四x+1
res2 = (lambda x: x + 1 if x >= 4 else print('res2 =', x))(3)

# 计算圆的面积
import math
res3 = lambda r: math.pi * r * r
print('res3=', res3(10))

应用场景:

​ 匿名函数通常配合其他函数一起使用,用于减少代码

匿名集合内置函数使用

求最大值 : max()

l1 = [11, 1131, 266, 6655, 22, 6659, 2, 6]
max_num = max(l1)
print(max_num)	# 6659

dic1 = {'jason': 1000, 'zhang': 1000000, 'fhao': 55555, 'cai': 11111}
# def index(k):
#    return dic1.get(k)	得到k的v
# richer = max(dic1,key=index)
richer = max(dic1, key=lambda k: dic1.get(k))
print(richer)	# zhang

求最小值 : min()

l1 = [11, 1131, 266, 6655, 22, 6659, 2, 6]
min_numb = min(l1)
print(min_numb)	# 2

dic1 = {'jason': 1000, 'zhang': 1000000, 'fhao': 55555, 'cai': 11111}
poor = min(dic1,key=lambda k:dic1.get(k))
print(poor)	# jason

映射 : map()

l1 = [11, 22, 33, 44, 55, 66, 77]
l2 = []
# 方式一
for i in l1:
    i += 20
    l2.append(i)
print(l2)
# 方式二
l3 = (i + 20 for i in l1)
print(list(l3))
# 方式三
res = map(lambda x:x+20,l1)
print(list(res))

def index(a):
    return a+20
res = map(index,l1)
print(list(res))

移除 指定值 : filter()

name_list = ['jason', 'kevin', 'oscar', 'jerry', 'tony']
# 方式一
for i in name_list:
    if i == 'tony':
        name_list.remove(i)
print(name_list)
# 方式二
name_list = ['jason', 'kevin', 'oscar', 'jerry', 'tony']
l2 = (i for i in name_list if i != 'kevin')
print(list(l2))
# filter()
name_list = ['jason', 'kevin', 'oscar', 'jerry', 'tony']
res = filter(lambda a: a != 'jerry', name_list)
print(list(res))

将很多单体 变成一个整体 : reduce()

# 求和
l1 = [1, 2, 3, 4]
# 方式一
c = 0
for i in l1:
    c += i
print(c)

# 方式二
res = sum(l1)
print(res)

# 方式三
from functools import reduce

res = reduce(lambda x, y: x + y, l1)
print(res)

zip()

​ 作用:可以将多个序列(列表、元组、字典、字符串以及range()区间构成的列表)压缩成一个zip对象,也就是将这些序列中对应的位置元素重新组成一个个新的元组

# 两个数量相同的列表
l1 = [1,2,3]
l2 = ['wang','zhang','zzz']
res2 = zip(l2,l1)
print(dict(res2))
# 列表与字符串
l1 = [1,2,3,4]
l2 = [5,6,7,8]
n3 = 'bcdn'
res3 = zip(l1,l2,n3)
print(list(res3))
# 数据值数量不同的列表,以及不同类型的数据
n1 = [1,2,3,4,5,6,7,8,9]
n2 = [11,22,33,44]
n3 = 'zhang'
res1 = zip(n1, n2, n3)
print(list(res1))
# 多出来的部分会舍弃

作业

多层装饰器

1.首先要调用函数,形成内在:index
2.开始穿衣服打扮,内在(index())---> 里衣(outter2) ---> 外衣(outter1)
3.开始脱衣服展示,外衣的里面(wrapper1) ===》里衣的里面(wrapper2) ===》内在(from index)

有参装饰器

1.首先要调用函数,形成内在:index
2.今天的天气(春、夏、秋、冬)
3.穿衣服:内在(index())---> 选春/夏/秋/冬(装饰器参数)--->给谁穿(login_auth)--->穿春装/夏装/秋装/冬装(inner)

标签:jason,函数,res,生成式,list,匿名,l1,print,name
来源: https://www.cnblogs.com/Zhang614/p/16456012.html