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

前端 未结 6 580
庸人自扰
庸人自扰 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:49

    list(map(cube, range(1, 11)))
    

    is equivalent to

    [cube(1), cube(2), ..., cube(10)]
    

    While the list returned by

    list(filter(f, range(2, 25)))
    

    is equivalent to result after running

    result = []
    for i in range(2, 25):
        if f(i):
            result.append(i)
    

    Notice that when using map, the items in the result are values returned by the function cube.

    In contrast, the values returned by f in filter(f, ...) are not the items in result. f(i) is only used to determine if the value i should be kept in result.


    In Python2, map and filter return lists. In Python3, map and filter return iterators. Above, list(map(...)) and list(filter(...)) is used to ensure the result is a list.

提交回复
热议问题