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 map, although I have seen both in various Python questions here on SO.
After reading about them in the Python tutorial, I'm confused on the difference between the two. For example, from 5.1.3. Functional Programming Tools:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
and
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
These looked almost exactly the same in function to me, so I went into terminal to run Python interactively and tested out my own case. I used map
for both the first and second instances above, and for the first one ( return x % 2 != 0 and x % 3 != 0
) it returned a list of booleans rather than numbers.
Why does map
sometimes return a boolean and other times the actual return value?
Can someone explain to me exactly the difference between map
and filter
?
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.
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]
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.
Filter--Returns the true value's position
var_list = [10,20,0,1]
var_b = list(filter(lambda var_a : var_a*2,var_list))
print("Values are",var_b)
Output
Values are [10, 20, 1]
Map--Returns the actual result
var_list = [10,20,0,1]
var_b = list(map(lambda var_a : var_a*2,var_list))
print("Values are",var_b)
Output
Values are [20, 40, 0, 2]
Reduce--Take the first 2 items in the list,then calls function, In next function call,the result of previous call will be 1st argument and 3rd item in list will be 2nd argument
from functools import *
var_list = [10,20,0,1]
var_b = list(map(lambda var_a : var_a*2,var_list))
print("Values of var_b ",var_b)
var_c = reduce(lambda a,b:a*2,var_b)
print("Values of var_c",var_c)
Output
Values of var_b [20, 40, 0, 2]
Values of var_c 160
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()
Filter function is used to filter results from our original list whereas Map function is used to apply some function on our original list and a new list is hence generated. See below examples where filter function is used to return items in list only when they are odd. Map function is used in below to return square of each item in list.
Lambda function: Using Lambda : Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.
g = lambda x: x*x*x
print(g(5))
#125
The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is a small program that returns the odd numbers from an input list:
li = [4,5,7,8,9]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)
#[5,7,9]
The map() function in Python takes in a function and a list as argument. A new list is returned by applying function to each item of list.
li = [5, 7, 4, 9]
final_list = list(map(lambda x: x*x , li))
print(final_list)
#[25, 49, 16, 81]
来源:https://stackoverflow.com/questions/18939596/python-difference-between-filterfunction-sequence-and-mapfunction-sequence