python进阶

python把函数作为参数

1
2
3
4
def add(x, y, f):
return f(x) + f(y)
add(-5, 9, abs)
# 其实是调用 abs(-5) + abs(9)

常用函数

  1. map()函数

    1
    2
    3
    4
    def f(x):
    return x*x
    print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    # 输出 [1, 4, 9, 10, 25, 36, 49, 64, 81]
  2. reduce()函数

    1
    2
    3
    def f(x, y):
    return x + y
    print reduce(f, [1, 3, 5, 7, 9])
  3. filter()函数

    1
    2
    3
    4
    def is_odd(x):
    return x % 2 == 1
    filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
    # 输出 [1, 7, 9, 17]
  4. sorted()函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    sorted([36, 5, 12, 9, 21])  # 排序

    def reversed_cmp(x, y):
    if x > y:
    return -1
    if x < y:
    return 1
    return 0
    sorted([36, 5, 12, 9, 21], reversed_cmp)
    # 输出 [36, 21, 12, 9, 5]
  5. 装饰者模式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    from functools import reduce
    def log(f):
    def fn(x):
    print('call ' + f.__name__ + '()...')
    return f(x)
    return fn

    @log # 指定被装饰的方法
    def factorial(n):
    return reduce(lambda x,y: x*y, range(1, n+1))
    print(factorial(10))
  6. 偏函数

    1
    2
    3
    import functools
    int2 = functools.partial(int, base=2)
    # int2就是一个偏函数
lightquant wechat
欢迎您订阅灯塔量化公众号!