美文网首页
python高阶函数

python高阶函数

作者: 是东东 | 来源:发表于2022-09-04 20:10 被阅读0次

    map

    old_list = [2, 3, 4]
    doubled_list = map(lambda x: x * 2, old_list)
    print(list(doubled_list))  # [4, 6, 8]
    

    product

    numbers = [2, 3, 4]
    summation = functools.reduce(lambda x, y: x * y, numbers)
    print(summation)  # 24
    

    filter

    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    res = list(filter(lambda x: x % 2 == 0, numbers))
    print(res)  # [0, 2, 4, 6, 8]
    

    zip

    keys = ['a', 'b', 'c', 'd', 'e']
    vals = [0, 1, 2, 3, 4]
    res = dict(zip(keys, vals))
    print(res)  # {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
    

    sort

    numbers = [0, 1, 2, 3, 4]
    res = sorted(numbers, reverse=True)
    print(res)  # [4, 3, 2, 1, 0]
    

    accumulate

    a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
    resutls = list(itertools.accumulate(a))
    # [3, 7, 13, 15, 16, 25, 25, 32, 37, 45]
    resutls = list(itertools.accumulate(a, max))
    # [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
    resutls = list(itertools.accumulate(a, lambda x, y: x * y))
    [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
    

    permutations

    import itertools
    nums = ['a','b','c']
    for num in itertools.permutations(nums):
        print(num)
    # ('a', 'b')
    # ('b', 'a')
    

    相关文章

      网友评论

          本文标题:python高阶函数

          本文链接:https://www.haomeiwen.com/subject/qdeunrtx.html