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

前端 未结 6 586
庸人自扰
庸人自扰 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条回答
  •  猫巷女王i
    2021-01-30 17:44

    filter(function, iterable) function (pointer, like in C) return boolean type

    map(function, iterable) function (pointer, like in C) return e.g. int

    def filterFunc(x):
        if x & 1 == 0:
            return False
        return True
    
    
    def squareFunc(x):
        return x ** 2
    
    
    def main():
        nums = [5, 2, 9, 4, 34, 23, 66]
        odds = list(filter(filterFunc, nums))   # filter(function, iterable)
        print(odds)
    
        square = list(map(squareFunc, nums))    # map(function, iterable)
        print(square)
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题