zoukankan      html  css  js  c++  java
  • python基础12_匿名_内置函数

    一个二分查找的示例:

    # 二分查找 示例
    data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35, 36, 66]
    
    
    def binary_search(dataset, find_num):
        print(dataset)
    
        if len(dataset) > 1:
            mid = int(len(dataset) / 2)
            if dataset[mid] == find_num:  # find it
                print("找到数字", dataset[mid])
            elif dataset[mid] > find_num:  # 找的数在mid左面
                print("33[31;1m找的数在mid[%s]左面33[0m" % dataset[mid])
                return binary_search(dataset[0:mid], find_num)
            else:  # 找的数在mid右面
                print("33[32;1m找的数在mid[%s]右面33[0m" % dataset[mid])
                return binary_search(dataset[mid + 1:], find_num)
        else:
            if dataset[0] == find_num:  # find it
                print("找到数字啦", dataset[0])
            else:
                print("没的分了,要找的数字[%s]不在列表里" % find_num)
    
    
    binary_search(data, 66)

    关于匿名函数 lambda

    #!/usr/bin/env python
    # coding:utf-8
    
    # 这段代码
    # def calc(n):
    #     return n ** n
    #
    #
    # print(calc(10))
    
    # 换成匿名函数
    calc = lambda n: n ** n
    print(calc(3))
    
    ######
    # 匿名函数通常用简单逻辑,与其它函数配合使用
    lambda x, y, z: (x + 1, y + 1, z + 1)
    
    
    ### 编程的方法论:
    # 面向过程
    # 函数式
    # 面向对象
    def foo(name):
        print(name)
    
    
    def bar(name):
        print("my name is %s" % name)
    
    print(foo(bar('aa')))
    print('----------------')
    
    
    lis = [333,222,111,11,22,33,44,55,66,888]
    print(max(lis))
    
    dic = {'k1': 10, 'k2': 100, 'k3': 30}
    
    # print("用max来求dic的最大值:",max(dic.values()))
    print("用max来求dic的最大key值:", max(dic))
    print(dic[max(dic, key=lambda k: dic[k])])
    print('===========')

    ### 使用map 和匿名函数 求平方 res = map(lambda x: x ** 2, [1, 5, 7, 4, 8]) for i in res: print(i) print(res, type(res)) ## listx = [1, 2, 3, 4, 5, 6, 7] # 7 个元素 listy = [2, 3, 4, 5, 6, 7] # 6 个元素 listz = [100, 100, 100, 100] # 4 个元素 list_result = map(lambda x, y, z: x ** 2 + y + z, listx, listy, listz) print(list(list_result)) # 由于 lambda 中的 z 参数,实际是使用了 listz, 而 listz 里面只有 4 个元素, # 所以,只执行了 4 个元素的的计算。

    学了好几节的东西,放在一起了。

    ## 高阶函数: 1.函数接收的参数是一个函数名; 2.返回值中包含函数
    # 把函数当作参数传递给另外一个函数
    # def foo(n):
    #     print(n)
    #
    # def bar(name):
    #     print("My name is %s" % name)
    #
    # foo(bar)
    # foo(bar('alex'))
    
    def bar():
        print("from bar")
    
    def foo():
        print("from foo")
        return bar
    
    foo()()
    
    
    def handle():
        print("from handle...")
        return handle
    
    h = handle()
    h()
    
    
    def test1():
        print("from test1")
    
    def test2():
        print('from test2')
        return test1()
    
    test2()
    
    
    ### 尾调用: 在函数的最后一步调用另外一个函数(不一定是最后一行。)
    ## 优化:把递归放在最后一步。

    map  / reduce  / filter  跟大数据沾点边 

    #### map函数,第一个参数是方法,第二个参数是迭代器(可迭代对象)
    ## python2中,map的结果直接是列表
    
    msg = 'abcdefg'
    print(list(map(lambda x: x.upper(), msg)))  # 简洁,但可读性很差。
    
    
    lis = (11, 22, 33, 44, 55, 66,)
    
    def abc(x):
        return x // 2 + 1
    
    res = map(abc,lis) #也可以传一个自定义的函数
    for i in res:
        print(i)

    print(list(map(str,lis))) # 将列表值转为字符串
    #!/usr/bin/env python
    # coding:utf-8
    
    ## python2中可直接用。但是3中需要导入模块。
    from functools import  reduce
    
    lis = [3,4,5,7,32,22,11]
    print(reduce(lambda x,y:x+y,lis))
    
    # 用来合并一个序列
    # 带有初始值的 reduce
    print(reduce(lambda x,y:x+y, lis, 100))
    #!/usr/bin/env python
    # coding:utf-8
    
    ### filter函数 用来过滤迭代器,得到过滤出的对象
    
    lis = ['alex_sb', 'abc_tom', 'dadasb', 'jerry', 'hhui_sb']
    
    # 不保留 sb 结尾的元素
    res = list(filter(lambda x: not x.endswith('sb'), lis))
    print(res)
    
    
    ## 保留以 a 开头的元素
    print(list(filter(lambda y:y.startswith('a'),lis)))
    
    
    # filter 练习: 过滤出小于33岁的。
    dic = [
        {'name':'alex', 'age':99},
        {'name':'wpq', 'age':66},
        {'name':'bigs', 'age':44},
        {'name':'tom', 'age':22},
        {'name':'jerry', 'age':33},
    ]
    
    print(list(filter(lambda n: n['age']<=33, dic)))

    python中常用的一些内置函数,更详细的内置函数,可参考:http://www.runoob.com/python/python-built-in-functions.html

    #!/usr/bin/env python
    # coding:utf-8
    
    print(abs(-3)) # 求绝对值
    
    # 所有元素是否不为 0、''、False ,三样都没有,则返回True
    # 空列表、元组、字典都为True
    print(all(''))
    print(all([]))
    print(all(()))
    print(all({}))
    print(all(['2','1',''])) # 返回false
    print(all([2,1,0])) # 返回false
    
    # 与all不同,如果有一个非0,非空,非false,则返回True
    print(any(['2',''])) # 任何一个为真即返回True
    
    
    print(bin(9)) # 转为二进制
    print(hex(9)) # 转为16进制
    print(oct(9)) # 转为8进制
    
    
    print(bool(''))
    
    
    name='你好'
    ## 转码为字节
    print(bytes(name,encoding='utf-8'))
    print(bytes(name,encoding='utf-8').decode('utf-8'))
    
    print(bytes(name,encoding='gbk'))
    print(bytes(name,encoding='gbk').decode('gbk'))
    
    
    print(chr(46)) # 转为ascii码
    
    
    print(divmod(10,3)) # 10除3, 取出商和余
    
    
    str_dic="{'name':'alex'}"
    print(str_dic)
    dic = eval(str_dic)  # 识别字符串中的字典
    print(dic['name'])
    
    
    str2= '1+3+5*2'
    print(str2)
    print(eval(str2))  # 识别字符串中的表达式,并得出结果
    
    
    ## 可hash的数据类型即不可变数据类型。 不可hash的即可变类型
    ## 应用: 检验软件下载的hash
    ## 不能通过hash值反推原始值 。
    
    name ='alex'
    print(hash(name))
    print(hash(name))
    name = 'sb'
    print(hash(name))
    
    
    print(dir(hash))
    print(help(hash))
    
    
    print(globals()) ## 输出全局变量
    print(__file__)  ##当前文件路径
    
    def test():
        age=19
        print(globals())
        print('----------------------')
        print(locals()) ##输出当前作用域的变量
    
    test()

    有一个max的小练习:

    #!/usr/bin/env python
    # coding:utf-8
    
    dic = {'k11':3000,'k6':5000,'k3':6000,'k4':8000}
    
    print(max(dic.keys()))
    print(max(dic.values()))
    
    # 求出字典中最大值对应的key
    print(max(dic, key = lambda k:dic[k])) # max 和 min都支持第二个参数key 以什么为关键字
    print(max(dic, key = lambda k:dic[k]),max(dic.values())) # max 和 min都支持第二个参数key 以什么为关键字

    其它内置函数:

    # print()
    # input()
    # len()
    # type()
    # open()
    # tuple()
    # list()
    # int()
    # bool()
    # set()
    # dir()
    # id()
    # str()
    
    
    # print(locals())  #返回本地作用域中的所有名字
    # print(globals()) #返回全局作用域中的所有名字
    # ---------- 注意区别下面的关键字------------
    # global 变量
    # nonlocal 变量
    
    # 迭代器.__next__()
    # next(迭代器)
    # 迭代器 = iter(可迭代的)
    # 迭代器 = 可迭代的.__iter__()
    
    # range(10)
    # range(1,11)
    # print('__next__' in dir(range(1,11,2)))  # range是可迭代的,但不是迭代器
    
    # dir 查看一个变量拥有的方法
    # print(dir([]))
    # print(dir(1))
    #       一定要学会使用 dir 和 help 做断网开发
    # help 提供帮助
    # help(str)
    
    # 检测是否可调用 callable
    # print(callable(print))
    # a = 1
    # print(callable(a))
    # print(callable(globals))
    # def func():pass
    # print(callable(func))
    
    # import time
    t = __import__('time')  # 这种导入方式不常用 
    print(t.asctime())
    print(t.ctime())
    # help(t)
    
    # 某个方法属于某个数据类型的变量,就用 . 调用
    # 如果某个方法不依赖于任何数据类型,就直接调用: 内置函数 和 自定义函数
    
    # f = open('1.复习.py')
    # print(f.writable())
    # print(f.readable())
    
    # id
    # hash - 对于相同可hash数据的hash值在一次程序的执行过程中总是不变的
    #      - 字典的寻址方式,用到了hash方法
    print(hash(12345))
    print(hash('hsgda不想你走,assssssssssssssssssssssasdfffffffffffasdnklgkds'))
    print(hash('hsgda不想你走,assssssssssssssssssssssssdfffffffffffasdnklgkds'))
    print(hash(('1', 'aaa')))
    # print(hash([]))     # 不可hash
    
    # ret = input('提示 : ')
    # print(ret)
    
    print('我们的祖国是花园', end='')  # 指定输出的结束符
    print('我们的祖国是花园', end='	')
    print(1, 2, 3, 4, 5, sep='|')  # 指定输出多个值之间的分隔符
    
    f = open('file', 'w')
    print('aaaa', file=f)  # 如果给 print 一个文件句柄,则输出到文件
    f.close()
    
    import time for i in range(0, 101, 2): time.sleep(0.06) char_num = i // 2 per_str = ' %s%% : %s ' % (i, '*' * char_num) if i == 100 else ' %s%% : %s' % (i, '*' * char_num) print(per_str, end='', flush=True) # progress Bar 进度条模块 exec('print(123)') eval('print(123)') print(eval('1+2+3+4')) # 有返回值 print(exec('1+2+3+4')) # 没有返回值 # exec和eval都可以执行 字符串类型的代码 # eval有返回值 —— 有结果的简单计算 # exec没有返回值 —— 简单流程控制 # eval只能用在你明确知道你要执行的代码是什么 code = '''for i in range(10): print(i*'+') ''' exec(code)
    # eval 计算类
    # exec 流程类
    # compile 交互类
    
    # 使用 compile 编译文本
    code1 = 'for i in range(0,10): print (i)'
    compile1 = compile(code1, '', 'exec')
    exec(compile1)
    
    # code2 = '1 + 2 + 3 + 4'
    # compile2 = compile(code2,'','eval')
    # print(eval(compile2))
    
    # code3 = 'name = input("please input your name:")'
    # compile3 = compile(code3,'','single')
    # exec(compile3) #执行时显示交互命令,提示输入
    # print(name)
    # name #执行后name变量有值
    # "'pythoner'"
    
    
    # 复数 —— complex
    # 实数 : 有理数
    #         无理数
    # 虚数 :虚无缥缈的数
    # 5 + 12j  === 复合的数 === 复数
    # 6 + 15j
    
    # 浮点数(有限循环小数,无限循环小数)  != 小数 :有限循环小数,无限循环小数,无限不循环小数
    # 浮点数
    # 354.123 = 3.54123*10**2 = 35.4123 * 10
    # f = 1.781326913750135970
    # print(f)  # 过长的浮点数会损失一点精度
    
    print(bin(10))    # 二进制
    print(oct(10))    # 八进制
    print(hex(10))    # 16进制
    
    # print(abs(-5))
    # print(abs(5))
    
    print(divmod(7,2))   # div除法 mod取余
    print(divmod(9,5))   # 除余 得到元组
    
    # print(round(3.14159,3))
    # print(pow(2,3))   #pow幂运算  == 2**3
    # print(pow(3,2))
    # print(pow(2,3,3)) #幂运算之后再取余
    # print(pow(3,2,1))
    
    ret = sum([1,2,3,4,5,6])
    print(ret)
    
    ret = sum([1,2,3,4,5,6,10],)
    print(ret)
    
    # print(min([1,2,3,4]))
    # print(min(1,2,3,4))
    # print(min(1,2,3,-4))
    # print(min(1,2,3,-4,key = abs))
    
    # print(max([1,2,3,4]))
    # print(max(1,2,3,4))
    # print(max(1,2,3,-4))
    print(max(1,2,3,-4,key = abs))
    
    
    print(3>2==2)   # True

    继续补充:注意list作为函数的参数的问题

    def extlist(val, lis=[]):
        lis.append(val)
        return lis
    
    
    list1 = extlist(10)
    print(list1)
    list2 = extlist(123,[])
    print(list2)
    list3 = extlist('a')
    print(list3)
    print(list1)   # 这个结果将和list3一样,因为是可变数据类型。类似于 lis=[] 独立在函数之外
    
    
    print(5 + 12j)  # 实数 + 虚数 == 复数
    
    
    # 取某个 range中的数时,一定要list下,才能取得到

    slice , format , bytes , expr

    lis = [1,2,3,4,5]
    
    l2 = reversed(lis) # 保留原有列表,返回一个反向的迭代器
    print(l2)
    print(lis)
    
    s = slice(0,5,2)    # 切片
    print(lis[s])       # 等同于下面的切片
    print(lis[0:5:2])
    
    
    print(format('***','<20'))      # 左对齐
    print(format('***','>20'))      # 右对齐
    print(format('***','^20'))      # 居中对齐
    
    print(format(3,'b'))        # 转为二进制
    print(format(95,'c'))       # 转成 unicode字符
    print(format(13,'x'))       # 转成16进制
    
    
    print(bytes('你好',encoding='gbk'))
    print(bytes('你好',encoding='utf8'))              # 编码
    print(b'xe4xbdxa0xe5xa5xbd'.decode('utf8'))  # 解码
    
    a = 'abcd'
    print('hello %r' %a)   # %r 调用了 repr 方法
    print(repr(a))      # 变量原样输出 %r

    all , any , zip , filter , map , sorted

    # all 有一个False,即为False , any 是有一个True,即为 True
    print(all(['a', '', 123]))
    print(all(['a', 123]))
    print(all([0, 123]))
    
    print(any(['', True, 0, []]))
    
    # 拉链方法
    l = [1, 2, 3, 4, 5]
    l2 = ['a', 'b', 'c', 'd']
    l3 = ('*', '**', [1, 2])
    d = {'k1': 1, 'k2': 2}
    
    # for i in zip(l,l2):
    #     print(i)
    
    for i in zip(l, l2, l3, d):
        print(i)
    
    
    # filter 重要的过滤方法
    def is_odd(x):
        return x % 2 == 1
    
    # print(is_odd(9))   # True
    
    # 第一个参数只能是函数名,没有括号。第二个是可迭代对象
    ret = filter(is_odd,[3,6,7,9,12,17])
    # print(ret)
    for i in ret:
        print(i)
    
    # 例二  过滤字符串
    def is_str(x):
        return type(x) == str
    
    res = filter(is_str,[1,'alex',3,5,'abc',8])
    for i in res:
        print(i)
    
    
    # 例三 求100以内开方结果为整数的数
    from math import sqrt
    def func(n):
        res = sqrt(n)
        return res %1 ==0
    
    rs = filter(func,range(1,101))
    for i in rs:
        print(i)
    
    
    # 例四: 去除列表中的空元素
    def real_str(x):
        return x and str(x).strip()
    
    res = filter(real_str,[1,'alex',0,' ','  ',None])
    for i in res:
        print(i)
    
    
    ret = map(abs,[1,-4,6,-8])
    print(ret)
    for i in ret:
        print(i)
    
    
    # filter 执行了filter之后的结果集合 <= 执行之前的个数
            #filter只管筛选,不会改变原来的值
    # map 执行前后元素个数不变
          # 值可能发生改变
    
    l = [1,-4,6,5,-10]
    # l.sort()            # 在原列表的基础上进行排序
    # print(l)
    l.sort(key = abs)     # 带上处理函数的排序
    print(l)
    
    
    print(sorted(l,key=abs,reverse=True))      # 生成了一个新列表 不改变原列表 占内存
    print(l)
    
    l = ['   ',[1,2],'hello world']
    new_l = sorted(l,key=len)
    print(new_l)
  • 相关阅读:
    postman接口测试工具
    fiddler如何做弱网测试
    支付的测试点
    公交卡测试点
    http的请求方式及http和https的区别
    百度输入框测试点
    ADB常用命令
    Python 操作注册表
    App测试流程及测试点
    python3.7 打包成exe的一种方法 pyinstaller
  • 原文地址:https://www.cnblogs.com/frx9527/p/python_12.html
Copyright © 2011-2022 走看看