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

前端 未结 6 627
庸人自扰
庸人自扰 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 18:05

    map and filter function in python is pretty different because they perform very differently. Let's have a quick example to differentiate them.

    map function

    Let's define a function which will take a string argument and check whether it presents in vowel letter sequences.

    def lit(word):
        return word in 'aeiou'
    

    Now let's create a map function for this and pass some random string.

    for item in map(lit,['a','b','e']):
        print(item)
    

    And yes it's equivalent to following

    lit('a') , lit('b') , lit('e')
    

    simply it will print

    True
    False
    True 
    

    filter function

    Now let's create a filter function for this and pass some random string.

    for item in filter(lit,['a','b','e']):
        print(item)
    

    filter as the name implies, filters the original iterable and retents the items that return True for the function provided to the filter function.

    Simply it will print

    a
    e
    

    Fork it here for future reference, if you find this useful.

提交回复
热议问题