|
Anonymous functions (lambdas) and map in Python
Why do you name variables? So that you can use them again later. But if you don't want to use them more than once, why bother with a name at all? Most programming languages create temporary or anonymous variables within a single line, and if you've programmed almost anything, you'll have used them without realising it.
In Python, everything is an object - and that includes functions. And so, just as you're allowed anonymous scalars and lists, you're allowed anonymous functions. They're defined using the lambda keyword ....
Here are some function definitions ....
def cricket(input):
return input/11
rugby = lambda x: (x-7)/15
games = (cricket,
rugby,
lambda input:input/2,
lambda x:x)
# and some data for the rest of the example
people = [150,175,210,50]
Let's now see some examples of how these functions are called, via the map function:
teams = map(cricket, people)
print "cricket - ",teams
teams = map(rugby, people)
print "rugby - ",teams
# Call a new (anonymous) function
teams = map(lambda x: x/7, people)
print "water polo - ",teams
# Loop through and call a list of functions
for k in range(0,len(games)):
teams = map(games[k], people)
print "seasonal - ",teams
Here are the results of running that code:
earth-wind-and-fire:~/nov08 grahamellis$ python mutton
cricket - [13, 15, 19, 4]
rugby - [9, 11, 13, 2]
water polo - [21, 25, 30, 7]
seasonal - [13, 15, 19, 4]
seasonal - [9, 11, 13, 2]
seasonal - [75, 87, 105, 25]
seasonal - [150, 175, 210, 50]
earth-wind-and-fire:~/nov08 grahamellis$
Full source code here ... learn more about this on our Python course (written 2008-11-04 18:32:19)
Associated topics are indexed under Y105 - Python - Functions, Modules and PackagesY111 - Python - More on Collections and Sequences
Some other Articles
List Comprehensions in PythonBarack Obama wins US PredidencyOptional and named parameters in PythonWhat to do with a huge crop of applesAnonymous functions (lambdas) and map in PythonLiverpool - a friendly cityDomain Renewal GroupWhat a difference a day madeDebugging and Data::Dumper in PerlObject Oriented Perl - First Steps
|
1975 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|