How to get filter to work with a lambda taking multiple arguments?

后端 未结 9 1059
闹比i
闹比i 2020-12-08 22:11

Using Python, am finding it difficult to get filter() to work with lambda for cases where more than 1 argument needs to be passed as is the case in the following snippet:

相关标签:
9条回答
  • 2020-12-08 22:32

    The function passed to filter() only gets a single argument passed to it, which is the current element in the iterable being iterated.. If you need something fancier than that then filter() won't do.

    0 讨论(0)
  • 2020-12-08 22:33

    I hope you are aware of?

    >>> max([1, 4, 8])
    8
    

    filter() takes a single argument. In your case, it will take 1. Then 4. Then 8.

    0 讨论(0)
  • 2020-12-08 22:34

    I'm in agreement with both @walkingpendulum and @Wesley, depending on the interpretation of the actual problem statement. So parsing through the ambiguity in the problem statement: If you're sequentially comparing one item to its previous value in an iterable object, a lambda expression is overkill, just use a list comprehension:

    [1 if i < i+1 else 0 for i in sequence1]
    

    If you're comparing objects, then just compare them -- a lambda expression wouldn't work firstly because you're only passing one argument where the lambda expression you defined you're passing three and lambda is generally applied across an iterable object. To compare objects, there are simple constructs for that:

    sequence1 == some_other_sequence
    

    and

    x, y, z = 1, 2, 3
    x < y < z
    

    And lastly, if you want to apply a lambda expression to an iterable object, map can get you there: (arbitrary lambda function)

    map(lambda x: x > 1, sequence1)
    

    Otherwise @walkingpendulum and @Wesley cover the other interpretations

    0 讨论(0)
  • 2020-12-08 22:35

    It's possible to do this using a closure:

    >>> def foo(a,b):
    ...   def bar(c):
    ...     return a+b+c
    ...   return bar
    ... 
    >>> x = foo(1,2)
    >>> x(3)
    6
    >>> y = foo(100,0)
    >>> y(1)
    101
    >>> x(1)
    4
    
    0 讨论(0)
  • 2020-12-08 22:44

    You could change

    max_validation = lambda x,y,z: x < y < z
    

    to

    max_validation = lambda (x,y,z): x < y < z
    
    0 讨论(0)
  • 2020-12-08 22:50

    Straight from the docs of Python Filters

    Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

    So, you can just process single arguments with Python filters. That effectively means you cannot use filters for the your example. You would have to write custom-code for the same.

    0 讨论(0)
提交回复
热议问题