Python: Difference between filter(function, sequence) and map(function, sequence)

前端 未结 6 575
庸人自扰
庸人自扰 2021-01-30 17:13

I\'m reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never

6条回答
  •  隐瞒了意图╮
    2021-01-30 17:48

    filter(), as its name suggests, filters the original iterable and retents the items that returns True for the function provided to filter().

    map() on the other hand, apply the supplied function to each element of the iterable and return a list of results for each element.

    Follows the example that you gave, let's compare them:

    >>> def f(x): return x % 2 != 0 and x % 3 != 0
    >>> range(11)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> map(f, range(11))  # the ones that returns TRUE are 1, 5 and 7
    [False, True, False, False, False, True, False, True, False, False, False]
    >>> filter(f, range(11))  # So, filter returns 1, 5 and 7
    [1, 5, 7]
    

提交回复
热议问题