List Comprehensions |
reduce() |
A "list
comprehension" is an expression that constructs a new
list using the elements from another list.
Its simplest form is: A somewhat more complicated list comprehension has an addition which
can select which expressions will end up in the new list, and which will
not. This is a replacement (or alternative) to the filter()
function in Python and many other languages. Here are some examples: >>> p = [3, -1, 12, 5, -2] >>> def double(n): >>> q = [
k%2 for k in p ] # 1 if odd, 0 if
even >>> q
= [ k for k in p if k > 0 ] #
selects positive ones
|
reduce(calc-function, list)
is a function which applies the calc-function to the
elements of a list to end up reducing the list to a resultant single
value. For instance, reduce() can apply the
addition-function to calculate the sum of the elements of a list.
The calc-function that you give to reduce() must take two arguments and return a value. reduce() will give the first 2 elements of the list (the second argument) to calc-function and calc-function will return a result (we'll call it r). reduce() will then give r and the third element of the list to calc-function and assign the result back to r. reduce() will give r and the 4th element to calc-function and assign the result back to r. It will continue to do this until it runs out of elements of the list. It returns r. Examples: >>> def add(x,y): Lambda-expressions: This is a mechanism of creating an "anonymous" (or un-named) function. Notice that reduce() expects a function as its first argument. In the example above, we only needed to define the add() function so that we could pass it on to reduce(). But with a lambda-expression, we can define the equivalent of the add() function directly inside first the argument to reduce() (and never have to give it a name). Here a simple form of a lambda-expression that adds two numbers together: lambda x,y: x+y We can then place this into the first argument to reduce(): >>> print reduce(lambda
x,y: x+y,p) if-else expressions: This is an expression of the form: expression-1 if true-false-test else expression-2 It returns expression-1 if the true-false-test is True, otherwise it returns expression-2. For instance: >>> p = 5 We can use all 3 constructs above (reduce(), lambda-expression and if-else) to calculate and print the largest element of a list: >>> p = [4, 7, 2, 1, 6] |