python中filter|map函数传入多个参数的方法

方法一:借助lambda

  • filter
    def foo(a, b, c):
        return a < b and b < c
    
    myTuple = (1, 2, 3, 4, 5, 6)
    
    # 找到大于1,小于4的值
    print(list(filter(lambda x: foo(1, x, 4), myTuple)))
    # (2, 3)
    
  • map
    def func(x, y):
        print(x, y)
        return x + y
    
    a = [1, 2]
    data = list(map(lambda x: func(x, 88), a))
    print(data)
    # 1 88
    # 2 8
    # [89, 90]
    

方法二: 借助partial

  • filter
    from functools import partial
    
    
    def foo(a, b, c):
        return a < b and b < c
    
    myTuple = (1, 2, 3, 4, 5, 6)
    print(list(filter(partial(foo, 1, c=4), myTuple)))
    (2, 3)
    
  • map
    from functools import partial
    
    
    def func(x, y):
        print(x, y)
        return x + y
    
    a = [1, 2]
    print(list(map(partial(func, y=88), a)))
    # 1 88
    # 2 8
    # [89, 90]
    

文章来源

  • Python list filtering with arguments

你可能感兴趣的:(Python,python,filter)