zoukankan      html  css  js  c++  java
  • 函数式编程->map



    # 函数式编程之map
    """
    num_l = [1, 2, 10, 5, 3, 7]
    # 需求1:对每个之执行平方
    # 方法1:for 循环
    ret = []
    for i in num_l:
    ret.append(i**2)
    # 方法2:对上面的过程进行封装
    def map_test(array):
    ret = []
    for i in array:
    ret.append(i**2)
    return ret

    # 需求2:队列表的每个值自增1
    def map_test(array):
    ret = []
    for i in array:
    ret.append(i+1)
    return ret
    # 需求3:队列表的每个值自减1
    def map_test(array):
    ret = []
    for i in array:
    ret.append(i-1)
    return ret
    # 需求N:....

    # 怎么应对上面的情况?
    def add_one(i):
    return i + 1
    def reduce_one(i):
    return i - 1
    def map_test(func, array):
    ret = []
    for i in array:
    ret.append( func(i))
    return ret
    print(map_test(add_one, [1, 2, 3, 4])) # 这也是一种高阶函数, [2, 3, 4, 5]
    # add_one改写
    print(map_test(lambda x:x+1, [1, 2, 3, 4])) # [2, 3, 4, 5]
    print(map_test(lambda x:x-1, [1, 2, 3, 4])) # [0, 1, 2, 3]

    # map就是map_test的功能
    print(map(lambda x:x+1, [1, 2, 3, 4])) # <map object at 0x102979f60>
    res = map(lambda x:x+1, [1, 2, 3, 4])
    for i in res:
    print(i)
    # print(list(res)) 两种输出都可以,notes:只能迭代一次.
    print(list(map(lambda x:x+1, [1, 2, 3, 4])))
    print(list(map(add_one, [1, 2, 3, 4]))) # 实现简单,难读
    # notes, map的第二个参数是可迭代对象即可.
    # map的第一个参数可以传入函数,或者是lamda.
    print(list(map(lambda x:x.upper(), "supter"))) # ['S', 'U', 'P', 'T', 'E', 'R']
    """




    """
    # map filter
    movie_people = ["sb_alex", "sb_wupeiqi", "sb_yuanhao", "haha1", "hsha2"]
    ret = []
    for p in movie_people:
    if not p.startswith("sb"):
    ret.append(p)
    print(ret)

    # 函数封装
    def filter_test(array):
    ret = []
    for p in array:
    if not p.startswith("sb"):
    ret.append(p)
    return ret
    print(filter_test(movie_people))
    """
    # 改造方式和上面一样,最终的程序结果是
    movie_people = ["sb_alex", "sb_wupeiqi", "sb_yuanhao", "haha1", "hsha2"]
    def filter_test(func,array):
    ret = []
    for p in array:
    if not func(p):
    ret.append(p)
    return ret
    print(filter_test(lambda n:n.startswith("sb"),movie_people)) # ['haha1', 'hsha2']

    # filter
    movie_people = ["sb_alex", "sb_wupeiqi", "sb_yuanhao", "haha1", "hsha2"]
    print("filter", list(filter(lambda n:n.startswith("sb"), movie_people)))
  • 相关阅读:
    BZOJ 1977: [BeiJing2010组队]次小生成树 Tree( MST + 树链剖分 + RMQ )
    BZOJ 2134: 单选错位( 期望 )
    BZOJ 1030: [JSOI2007]文本生成器( AC自动机 + dp )
    BZOJ 2599: [IOI2011]Race( 点分治 )
    BZOJ 3238: [Ahoi2013]差异( 后缀数组 + 单调栈 )
    ZOJ3732 Graph Reconstruction Havel-Hakimi定理
    HDU5653 Bomber Man wants to bomb an Array 简单DP
    HDU 5651 xiaoxin juju needs help 水题一发
    HDU 5652 India and China Origins 并查集
    HDU4725 The Shortest Path in Nya Graph dij
  • 原文地址:https://www.cnblogs.com/Windows-phone/p/9729845.html
Copyright © 2011-2022 走看看