python基础14 三元表达式与函数补充

344 阅读6分钟

三元表达式

  • 此时我们有几个需求
    • 1.获取用户输入的用户名,如果是jason就打印欢迎,不然答应滚蛋。
    1.此时我们想到的是通过获取用户名判断,但是这样代码会觉得有点冗余。
    username = input('用户名').strip()
    if username == 'jason' :
        print('欢迎jason')
    else:
      print('滚蛋')
    
    所以此刻我们可以用到三元表达式
    
    username = input('用户名').strip()
    print('欢迎') if username=='jason' else print('滚蛋')
    
    • 2.编写一个函数,比较两个数的大小,返回较大的哪个
    2.我们会想到通过分支判断,来解决。
    def func(a,b):
       if a>b:
           return a
       else:
           return b
    res = func(1,10)
    print(res)
    
    通过三元表达式:
    def func(a,b):
        return a if a>b else b
    res = func(1,234)
    print(res)
    
  • 所以我们得出三元表达式能够有效减少一些代码的运行
    • 1.三元表达式只能比较有两种结果二选一的情况
    • 2.且三元表达式一般不建议嵌套使用
    res = 503 if 21 > 18 else (110 if 1 else(120 if 0 else 119))
    
  • 三元表达式有固定的语法结构:
    数据值1 if 条件 else 数据值2 
    
    • 如果满足条件输出if前的数据值,如果不满足条件输出else后面的数据值
    • 如果条件出现布尔值,True输出if前的数据值,False输出else后的数据值

各种生成式


name_list = ['jason', 'kevin', 'oscar', 'jerry', 'tony']
   
   给上述列表中所有的数据值加上_NB的后缀:

我们会想到:
# 1.定义一个空列表用于存放即将传入的数据值
# 2.循环原列表的所有数据
# 3.给name_list中的数据值拼接_NB后缀        
# 4.将添加后缀后的数据值添加到新的空列表    
# 5.输出新列表
    new_list = []
    for name in name_list:
        new_name = name + '_nb'
        new_list.append(new_name)
    print(new_list)
  • 列表生成式
但是我们如果使用列表生成式就会大幅减少代码量:
new_list = [name + '_nb' for name in name_list]
print(new_list)
** 除打印外的操作都在列表内部完成,得到的数据值就不需要添加进列表了,因为已经在了

# 语法式固定,运行流程为:
# 1.定义一个new_list[]
# 2.运行for循环后面的(循环name_list的数据值)
# 3.运行for前面的让循环的数据值都加_nb
# 4.输出得到的列表

** 列表生成式还可以进行if判断,并且里面只能出现for和if
  • 字典生成式
new_dict ={i :'jason' for i in range(10) if i == 6}
print(new_dict)
1.新建字典new_dict{}
2.for循环093.if 如果等于6
4.将6作为字典的k值给字典
5.输出得到的字典就是6 : 'jason
  • 集合生成式
new_set = {name for name in name_list if name == 'jason'}
print(new_set)
1.空列表 new_set
2.列表内for循环
3.if判断
4.for前面的需求
5.输出列表
  • 元组生成式
元组没有生成式这种说法,但是他有迭代器(生成器),是重要的知识,后面才会学习。

匿名函数

  • 匿名函数就是没有函数名的函数
  • 匿名函数通常配合其他函数一起使用,目的是为了减少代码
  • 语法结构:
    lambda 形参: 返回值
    
# 具体案例
#  (lambda x: x + 1)(123)  直接调用
#     res = lambda x: x + 1  命名调用
#   print(res(123))

内置函数

  • max()/min()

    • 求最大值max()

      1
      num = [1,4,2,6,5,7,4,4,67]
      res = max(num)
      print(res)
      
      例2
      dict = {
          'tom': 18,
          'jack': 20,
          'aim': 28,
          'bob': 43
      }
       # 方法一:
       def index(k):
           return dict.get(k)
       res = max(dict,key=index)
       print(res)
       # 方法二:匿名函数
       res = max(dict,key=lambda k: dict.get(k)
      
         #要注意不要进行k值比对
      
      
    • 求最小值min() 与max方法相同不过输出的是最小值

  • map()

    • map()映射
      l1 = [11, 22, 33, 44, 55, 66]
      # 需求:将列表中所有的数据值自增20.有什么方式呢
      # 方式1:for循环
      # 方式2:列表生成式
      # 方式3:map函数
      res = map(lambda x: x + 20, l1)
      print(res)  # <map object at 0x000001954B581100>
      print(list(res))
      def index(a):
          return a + 20
      res = map(index, l1)
      print(list(res))
      
  • filter()过滤

    l1 = ['jason', 'kevin', 'oscar', 'tony']
    # 需求:移除数据值里面的jason
    # 方式1:for循环
    # 方式2:列表生成式
    # 方式3:filter()
    res = filter(lambda a: a != 'jason', l1)
    print(res)  # <filter object at 0x00000195F21E6C70>
    print(list(res))  # ['kevin', 'oscar', 'tony']
    def index(a):
        return a != 'jason'
    res = filter(index, l1)
    print(list(res))
    
  • reduce()归总

    l2 = [1, 2, 3]
    # 需求:求列表中所有数据值的和
    # 方式1:for循环
    # 方式2:sum()
    res = sum(l2)
    print(res)
    # 方式3:reduce()   将很多单体 变成一个整体
    from functools import reduce
    
    res = reduce(lambda x, y: x + y, l2, 100)
    
    print(res)
    
  • zip()拉链

    n1 = [1, 2, 3]
    n2 = ['jason', 'kevin', 'oscar']
    res = zip(n1, n2)
    print(res)  # <zip object at 0x000002A9E38C7F40>
    print(list(res))
    

作业

多层解释器

def outter1(func1):                        # 1.定义函数outter1设置参数func1
                                           # 18.func1其实就是warpper2
    print('输出outter1')                    # 19.打印  输出哦outter1
    def wrapper1(*args, **kwargs):         # 20.定义warpper1
        print('输出wrapper1')               # 24
        res1 = func1(*args, **kwargs)      # 25  func1是warpper2,调用函数warpper2
        return res1                        # 34
    return wrapper1                        # 21.返回warpper1

def outter2(func2):                        # 2.定义函数outter2设置参数func2
                                           # 11.func2其实就是warpper3
    print('输出outter2')                    # 12.打印  输出outter2
    def wrapper2(*args, **kwargs):         # 13.定义warpper2
        print('输出wrapper2')               # 26
        res2 = func2(*args, **kwargs)      # 27 调用函数warpper3
        return res2                        # 33
    return wrapper2                        # 15.返回wrapper2

def outter3(func3):                        # 3.定义函数outter3设置参数func3
                                           # 5.func3其实就是真正的index
    print('输出outter3')                    # 6.打印   输出outter3
    def wrapper3(*args, **kwargs):         # 7.定义warpper3
        print('输出wrapper3')               # 28
        res3 = func3(*args, **kwargs)      # 29 调用index函数
        return res3                        # 32
    return wrapper3                        # 8.返回wrapper3

@outter1                # 17.outter1(warpper2)
                        # 22.接收返回值warpper1,此时函数名warpper1上面没有语法糖index=outter1(warpper2)
                        # 23.index其实是warpper1,调用函数warpper1
@outter2                # 10.outter2(warpper3)
                        # 16.接收返回值warpper2,此时函数名warpper2上面还是语法糖warpper2=outter2(warpper3)

@outter3                # 4.这一步实际是outter3(index)
                        # 9.接收返回值warpper3,此时函数名warpper3上面还是语法糖 warpper3=outter3(index)

# 语法糖的功能:会自动将下面紧挨着的函数名当作参数传递给@符号后面的函数名
                    # @outter1
                    # @outter2
                    # @outter3

def index():
    print('from index')     # 31
index()                     # 30

## 有参装饰器

def outer(condition,type_user): # 1 定义outer

def login_auth(func_name):                             # 3 定义login_auth

    def inner(*args, **kwargs):                        # 6 定义 inner
        username = input('username>>>:').strip()      #9
        password = input('password>>>:').strip()      #10
        # 应该根据用户的需求执行不同的代码
        if type_user =='jason':                   #11
            print('VIP')                          #12
        if condition == '列表':                       #11
            print('使用列表作为数据来源 比对用户数据')      #12
        elif condition == '字典':                    #11
            print('使用字典作为数据来源 比对用户数据')    #12
        elif condition == '文件':                   #11
            print('使用文件作为数据来源 比对用户数据')    #12
        else:                                      #11
            print('去你妹的 我目前只有上面几种方式')     #12
    return inner                         # 7 返回值 inner
return login_auth                        # 4 返回值login_auth
@outer('文件','jason')                        # 2 outer('文件','jason')传给函数outer
                                         # 5.@login_auth 语法糖变为 index=login_auth(index)
                                         # 8.index其实就是inner
def index():                                #13
print('from index')                         #15
index()                                     #14 调用index函数
```