Python list filtering with arguments

前端 未结 3 1765
离开以前
离开以前 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:02

    You can create a closure for this purpose:

    def makefilter(a, c):
       def myfilter(x):
           return a < x < c
       return myfilter
    
    filter14 = makefilter(1, 4)
    
    myList = [1, 2, 3, 4, 5, 6]
    filter(filter14, myList)
    >>> [2, 3]
    

提交回复
热议问题