For linked lists, there are three built-in functions that are useful: filter (), map (), and reduce ().
filter(function, sequence)
Returns an sequence (sequence) that includes the elements that return a value of true after all calls in a given sequence function(item)
(the same type is returned, if possible). If the sequence (sequence) is a str,unicode or a tuple, the return value must be the same type, otherwise it is always list. For example, the following program can calculate a sequence that is divisible by 3 and 5:
def F (x): return x 3 = = 0 and x 5 = = 0print filter (F,range (2,100))
[15, 30, 45, 60, 75, 90]
map(function, sequence)
Each element is called in turn function(item)
and the return value is returned as a linked list. For example, the following program outputs the elements in the list 3 times:
def Word (x): return x*3words = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ']print map (word,words)
[' 111 ', ' 222 ', ' 333 ', ' 444 ', ' 555 ', ' 666 ']
You can pass in more than one sequence, and the function must have a corresponding number of arguments, which, in turn, invoke the function with the corresponding elements on each sequence (if some sequences are shorter than others, use None
them instead). If None
a function is passed in, the parameter is returned as an alternative. For example:
SEQ1 = Range (8= range (9,17)def Add (x, y ):return x+y Print map (ADD,SEQ1,SEQ2) [9, 11, 13, 15, 17, 19, 21, 23]
reduce(function, sequence)
Returns a single value, which is constructed by invoking the function functions first with the first two elements of the sequence, then invoking the return value and the third argument, and sequentially executing. For example, the following program calculates the sum of integers 1 to 10:
def Add (x, y ): return x+yprint reduce (Add,range (1,11))
55
Functional use in Python