Python list filtering with arguments

前端 未结 3 1763
离开以前
离开以前 2021-02-03 21:25

Is there a way in python to call filter on a list where the filtering function has a number of arguments bound during the call. For example is there a way to do something like t

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-03 22:08

    One approach is to use lambda:

    >>> def foo(a, b, c):
    ...     return a < b and b < c
    ... 
    >>> myTuple = (1, 2, 3, 4, 5, 6)
    >>> filter(lambda x: foo(1, x, 4), myTuple)
    (2, 3)
    

    Another is to use partial:

    >>> from functools import partial
    >>> filter(partial(foo, 1, c=4), myTuple)
    (2, 3)
    

提交回复
热议问题