• Python 递归、匿名函数、map和filter day4


    一、递归---函数自己调用自己

    1、一个错误递归的例子:

    count=0
    def hello():
        global count
        count+=1
        print("count %s"%count)
        hello()
    
    hello()
    #递归最多循环999次,如上为死循环
    #1、用递归的时候一定要指定一个结束的条件
    #2、递归效率没有循环高,能不用递归就不用递归

    2、一个正确递归的例子:

    def test1():
        num = int(input('please enter a number:'))
        if num%2==0:#判断输入的数字是不是偶数
           return True #如果是偶数的话,程序就退出了,返回true
        print('不是偶数请重新输入!')
        return test1()#如果不是偶数的话继续调用自己,输入值
    print(test1())#调用test

    二、匿名函数

    没有名字的函数,不用写return,返回值就是该表达式的结果。

    语法:lambda 参数:方法(或三元运算)

    a1 = lambda x:x*x  #冒号前为入参 ,冒号后为返回值 ,只能传一个参数
    
    def a2(x):
        return x*x
    
    print(a1(3))
    print(a2(3))
    
    #a1等同于a2

    三、map和filter

    1、 map
    (1)map是循环帮你调用函数的
    (2)map会把函数每一次调用的返回值保存,最后返回

    #例子1:给列表每个元素增加1
    import os
    def choice(a):
        return a+1
    
    result = list(map(choice,[1,2,3,4,5,6]))
    print(result)#结果为[2, 3, 4, 5, 6, 7]
    
    #例子2:帮用户创建文件夹
    import os
    stus = ['hanmin','chunting','jiajinju','yll']
    for stu in stus:#老方法
        os.mkdir(stu)
    
    for stu in stus:
        os.rmdir(stu)#移除文件夹 执行完添加再执行添加会报错,需要删除空文件夹
    
    result= list(map(os.mkdir,stus))# 新方法;map为迭代器,必须转为list才可以执行
    print(result)

    2、filter
    (1)循环帮你调用函数
    (2)帮你过滤你传入的参数,函数的结果返回是true那就保存,返回false就不要了#

    #例子1:从1到6里找到偶数
    filter():‘筛选函数’,filter()把传人的函数依次作用于序列的每个元素,然后根据返回值是True还是false决定保留还是丢弃该元素,返回符合条件的序列 def func(x): return x%2==0 print(list(filter(func,range(1,6))))#结果为[2,4]
    #例子2:分数不及格的罚款
    stu_score = {'xiaobai':50,'xiaohei':30,'xiaolan':80,'xiaojun':100,
                 'xiaoming':60}
    
    for stu,score in stu_score.items():
        if score < 60:
            print("不及格:",stu)
    
    a=filter(lambda score:score<60,stu_score.values())
    b=list(a)
    print('result:',b)
    
    stu_score = [60,30,50,70,99,100,67]
    result = list(filter(lambda score:score>=60,stu_score))
    print(result)
    
    #如上代码等同于如下代码
    def panduan(score):
        return score >=60
    result = list(filter(panduan,stu_score))
    print(result)
  • 相关阅读:
    环境变量配置1
    Golang 类型转换,断言和显式强制转换
    Goland could not launch process: decoding dwarf section info at offset 0x0: too short 解决方案
    用puttygen工具把私钥id_rsa转换成公钥id_rsa.ppk
    JetBrains GoLand 2018 激活码/ 注册码(最新破解方法)
    Go学习笔记(只有链接)
    linux中的ftp命令
    Linux的学习之路
    like语句百分号前置会使用到索引吗?
    记录下每月生活开支
  • 原文地址:https://www.cnblogs.com/candysalty/p/11058727.html
Copyright © 2020-2023  润新知