What are Python's equivalent of the following (Javascript):
function wordParts (currentPart, lastPart) {
return currentPart+lastPart;
}
word = ['Che', 'mis', 'try'];
console.log(word.reduce(wordParts))
and this:
var places = [
{name: 'New York City', state: 'New York'},
{name: 'Oklahoma City', state: 'Oklahoma'},
{name: 'Albany', state: 'New York'},
{name: 'Long Island', state: 'New York'},
]
var newYork = places.filter(function(x) { return x.state === 'New York'})
console.log(newYork)
lastly, this:
function greeting(name) {
console.log('Hello ' + name + '. How are you today?');
}
names = ['Abby', 'Cabby', 'Babby', 'Mabby'];
var greet = names.map(greeting)
Thanks all!
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer (you) to write simpler, shorter code, without neccessarily needing to bother about intricacies like loops and branching.
The map function performs a transformation on each item in an iterable, returning a lazy iterable back. The filter function filters down items in an iterable, returning a lazy iterable back.
map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong. reduce , on the other hand, takes all of the elements in an array and reduces them into a single value. Just like map and filter , reduce is defined on Array.
Map: Apply the same set of steps to each item, storing the result. Filter: Apply validation criteria, storing items that evaluate True. Reduce: Return a value that is passed from element to element. What Makes Python Map/Filter/Reduce Different? In Python, the three techniques exist as functions, rather than methods of the Array or String class.
In the next example, filter () is used to get all the students whose grades are greater than or equal to 90. The reduce () method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.
If the condition returns false, the element does not get pushed to the output array. The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required. In the following example, odd numbers are "filtered" out, leaving only even numbers.
Just like .map (), .reduce () also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.
They are all similar, Lamdba functions are often passed as a parameter to these functions in python.
Reduce:
>>> from functools import reduce
>>> reduce( (lambda x, y: x + y), [1, 2, 3, 4]
10
Filter:
>>> list( filter((lambda x: x < 0), range(-10,5)))
[-10, -9, -8, -7, - 6, -5, -4, -3, -2, -1]
Map:
>>> list(map((lambda x: x **2), [1,2,3,4]))
[1,4,9,16]
Docs
reduce(function, iterable[, initializer])
filter(function, iterable)
map(function, iterable, ...)
https://docs.python.org/2/library/functions.html
It is worth noting that this question has been answered at face value above with the accepted answer, but as @David Ehrmann mentioned in a comment in the question, it is preferred to use comprehensions instead of map
and filter
.
Why is that? As stated in "Effective Python, 2nd Edition" by Brett Slatkin pg. 108, "Unless you're applying a single-argument function, list comprehensions are also clearer than the map
built-in function for simple cases. map
requires the creation of a lambda
function for the computation, which is visually noisy." I would add the same goes for filter
.
e.g. let's say I want to map and filter over a list to return the square of the items in the list, but only the even ones (this is an example from the book).
Using the accepted answer's method of using lambdas:
arr = [1,2,3,4]
even_squares = list(map(lambda x: x**2, filter(lambda x: x%2 == 0, arr)))
print(even_squares) # [4, 16]
Using comprehensions:
arr = [1,2,3,4]
even_squares = [x**2 for x in arr if x%2 == 0]
print(even_squares) # [4, 16]
So, along with others, I would advise using comprehensions instead of map
and filter
. This question dives into it even further.
As far as reduce
goes, functools.reduce
still seems like the proper option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With