zoukankan      html  css  js  c++  java
  • Python9-内置函数2-day16

    #zip方法

    l = [1,2,3]
    l2 = ['a','b','c']
    l3 = ('*','**',[1,2])
    l4 = {'k1':1,'k2':2}
    for i in zip(l,l2,l3,l4):
        print(i)

    #filter

    def is_odd(x):
        return x %2 == 1
    ret = filter(is_odd,[1,4,5,7,8,12])
    for i in ret:
        print(i)
    
    
    1
    5
    7

    #过滤字符串

    def is_str(s):
        return type(s)==str
    ret = filter(is_str,[1,4,5,'hello',7,8,'world',12])
    for i in ret:
        print(i)
    
    
    
    hello
    world

    #删除None和空字符串

    def is_str(s):
        if type(s) != int:
            return s and str(s).strip()
    
    ret = filter(is_str,[1,4,5,'hello','   ',[],None,7,8,'world',12])
    
    for i in ret:
        print(i)

     利用filter过滤出1-100中平方根的整数的数,

    from math import sqrt
    def func(num):
    res = sqrt(num)
    return res%1 == 0
    ret = filter(func,range(1,101))
    for i in ret:
    print(i)
    #map方法   执行一边abs
    ret = map(abs,[1,-2,-5,3])
    print(ret)
    for i in ret:
        print(i)
    1
    2
    5
    3
    #总结
    # filter 执行了filter之后的结果的集合 <=执行之前的个数
    # filter只管筛选,不会改变原来的值
    # map 执行前后元素个数不变
    # 值可能发生改变

    # sorted()

    l = [1,-4,6,5,-10]
    print(sorted(l))   #产生新的列表,不改变源列表,占内存
    print(l)
    print(sorted(l,reverse=True))

    [-10, -4, 1, 5, 6]
    [1, -4, 6, 5, -10]
    [6, 5, 1, -4, -10]


    列表长度从长到短排序
    l = ['    ',[1,2],'hello world']
    new_l = sorted(l,key=len,reverse=True)
    print(new_l)
    
    
    ['hello world', '    ', [1, 2]]

    #匿名函数

     

    add = lambda x,y:x+y
    print(add(1,2))
    
    3

     取出字典中的最大value对应的key

    dic = {'k1':2,'k5':100,'k3':4}
    print(max(dic,key=lambda k:dic[k]))

    k5
    面试题# (('a'),('b')),(('c'),('d'))---->[{'a': 'c'}, {'b': 'd'}]

    ret = zip((('a'),('b')),(('c'),('d')))
    # def func(tup):
    #     return {tup[0]:tup[1]}
    res = map(lambda tup:{tup[0]:tup[1]},ret)
    print(list(res))
    
    or
    
    res = list(map(lambda tup:{tup[0]:tup[1]},zip((('a'),('b')),(('c'),('d')))))
    print(res)

    or
    print(list(map(lambda tup:{tup[0]:tup[1]},zip((('a'),('b')),(('c'),('d'))))))
    [{'a': 'c'}, {'b': 'd'}]


  • 相关阅读:
    PHP+MySQL
    Appstore排名前十的程序员应用软件
    架构师的平凡之路
    程序员,如何三十而立?
    不懂技术也可以轻松开发一款APP
    php语法学习:轻松看懂PHP语言
    你真的了解软件测试行业吗?
    十个程序员必备的网站推荐
    从更高点看软件开发的侧重点
    php如何实现文件下载
  • 原文地址:https://www.cnblogs.com/zhangtengccie/p/10340562.html
Copyright © 2011-2022 走看看