Python Tutorial_ Lambda Operator, filter, reduce and map
Python Tutorial_ Lambda Operator, filter, reduce and map
Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact
Mostly, lambda is
used in mathematics
and computer
science: Lambda
denotes a Lagrange
multiplier in multi-
dimensional calculus.
Lambda stands for
the eigenvalue in the
mathematics of linear
algebra. Lambda
denotes the
Lebesgue measure in
mathematical set
theory. Lambda λ is
used to stand for an
empty string in
formal language
theory in computer
science. Lambda
denotes Christopher
Langton's parameter
for the classification
of Stephen Wolfram's
classes of cellular
automata.
What's interesting us
most in our Python
context is its usage
for anonymous
functions. It's both in
mathematical logic
and computer science
used to express the
concepts of the
lambda calculus. In
programming it had
become famous
Examples of reduce()
through the
programming Determining the maximum of a list of numerical values by using reduce:
language Lisp. Lisp
>>> from functools import reduce
programmers had >>> f = lambda a,b: a if (a > b) else b
been responsible for >>> reduce(f, [47,11,42,102,13])
it incorporation into 102
Python. >>>
It's very simple to change the previous example to calculate the product (the factorial) from 1 to a number, but do not choose 100. We just have to turn the "+" operator into "*":
If you are into lottery, here are the chances to win a 6 out of 49 drawing:
Order Number Book Title and Author Quantity Price per Item
34587 Learning Python, Mark Lutz 4 40.95
98762 Programming Python, Mark Lutz 5 56.80
77226 Head First Python, Paul Barry 3 32.95
88112 Einführung in Python3, Bernd Klein 3 24.99
Write a Python program, which returns a list with 2-tuples. Each tuple consists of a the order number and the product of the price per items and the quantity. The product should be increased by 10,- € if the
value of the order is less than 100,00 €.
Write a Python program using lambda and map.
2. The same bookshop, but this time we work on a different list. The sublists of our lists look like this:
[ordernumber, (article number, quantity, price per unit), ... (article number, quantity, price per unit) ]
Write a program which returns a list of two tuples with (order number, total amount of order).
min_order = 100
invoice_totals = list(map(lambda x: x if x[1] >= min_order else (x[0], x[1] + 10),
map(lambda x: (x[0],x[2] * x[3]), orders)))
print(invoice_totals)
min_order = 100
invoice_totals = list(map(lambda x: [x[0]] + list(map(lambda y: y[1]*y[2], x[1:])), orders))
invoice_totals = list(map(lambda x: [x[0]] + [reduce(lambda a,b: a + b, x[1:])], invoice_totals))
invoice_totals = list(map(lambda x: x if x[1] >= min_order else (x[0], x[1] + 10), invoice_totals))
print (invoice_totals)
© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein