• Python匿名函数


    1. 请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    复制代码
    1 import math
    2 def func(x):
    3     return math.sqrt(x) % 1 == 0
    4 ret = filter(func,range(0,101))
    5 for i in ret:
    6     print(i)
    复制代码


    2. 列表按照其中每一个值的绝对值排序

    li = [1,-2,3,-48,78,9]
    print(sorted(li,key = abs))

    结果:
    [1, -2, 3, 9, -48, 78]

    3. 列表按照每一个元素的len排序

    li = [(1,-2),[3],[-48,78,9],'hello world']
    ret = sorted(li,key = len) 
    print(ret)


    结果:
    [[3], (1, -2), [-48, 78, 9], 'hello world']

    4.请把以下函数变成匿名函数

    def add(x,y):
        return x+y



    改成匿名函数:
    ret = lambda x,y:x+y

    5. 下面程序的输出结果是:
    d = lambda p:p*2
    t = lambda p:p*3
    x = 2
    x = d(x)
    x = t(x)
    x = d(x)
    print (x)

    结果:
    24

    6. 现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

    # 看到匿名函数,就要想到肯定会带着考内置函数,而和匿名函数相关的内置函数只有5个:min max filter map sorted
    # 排除法想到map
    # 没用匿名函数

    tu1 =(('a'),('b'))
    tu2 =(('c'),('d'))
    res = zip(tu1,tu2)
    def func(tup):
        return {tup[0]:tup[1]}
    ret = map(func,res)
    # for i in ret:
    #     print(i)
    list(ret)

    # 用匿名函数

    复制代码
    tu1 =(('a'),('b'))
    tu2 =(('c'),('d'))
    res = zip(tu1,tu2)
    # def func(tup):
    #     return {tup[0]:tup[1]}
    ret = map(lambda tup:{tup[0]:tup[1]},res)
    # for i in ret:
    #     print(i)
    print(list(ret))
    复制代码

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

    7. 以下代码的输出是什么?请给出答案并解释。

    def multipliers():
        return [lambda x:i*x for i in range(4)]
    print([m(2) for m in multipliers()])


    请修改multipliers的定义来产生期望的结果。

    结果:
    [6, 6, 6, 6]

    def multipliers():
        return (lambda x:i*x for i in range(4))         # 改为生成器
    print([m(2) for m in multipliers()])

    结果:
    [0, 2, 4, 6]

  • 相关阅读:
    最简明的JavaScript闭包解释
    REST vs SOAP
    MAC Objective-C 开发经典书籍推荐
    测试word版博客文章
    Sitecore CMS中删除项目
    Sitecore CMS中如何命名项目名称
    Sitecore CMS中查看标准字段
    Sitecore CMS中配置项目图标
    如何在Sitecore CMS中创建项目
    如何在Sitecore CMS中管理桌面快捷方式
  • 原文地址:https://www.cnblogs.com/dongye95/p/10327645.html
Copyright © 2020-2023  润新知