This article is going to try to shed some light on how to convert map, reduce and filter (often used with lambda expressions) in python into a syntax conforming to...
This article is going to try to shed some light on how to convert map, reduce and filter (often used with lambda expressions) in python into a syntax conforming to “the python way”. At the bottom you will find a download link to execute this stuff for yourself.
l = range(10)
print l
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This is going to be the list (l) we’re working on.
What we’ll be looking at first, is iterating through this list and applying a function. And what simpler function could there be, than the identity?
a = map(lambda x: x, l)
b = list(x for x in l)
print a, b
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you don’t really know what the we did in (a) you may want to read up on lambda expressions, a topic I am not covering now. We need the list-method in (b) because map() always returns a list and the for-expression coughs up a generator object which we have to fully evaluate and convert to a list, to get the equivalent. Generator objects I will cover in the future. For now, suffice to say, it has a reason we are applying the list-function.
Weiterlesen →