12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Items in the sequence for which the function returns true are added to the result list.Like map, this function is roughly equivalent to a for loop, but is built-in, and fast:>>> res = [ ]>>> for x in range(-5, 5):... if x > 0:... res.append(x)...>>> res[1, 2, 3, 4]reduce is more complex. Here are two reduce calls computing the sum and productof items in a list:>>> reduce((lambda x, y: x + y), [1, 2, 3, 4])10>>> reduce((lambda x, y: x * y), [1, 2, 3, 4])24At each step, reduce passes the current sum or product, along with the next itemfrom the list, to the passed-in lambda function. By default, the first item in thesequence initializes the starting value. Here’s the for loop equivalent to the first ofthese calls, with the addition hardcoded inside the loop:>>> L = [1,2,3,4]>>> res = L[0]>>> for x in L[1:]:... res = res + x...>>> res10Coding your own version of reduce (for instance, if it is indeed removed in <strong>Python</strong> 3.0)is actually fairly straightforward:>>> def myreduce(function, sequence):... tally = sequence[0]... for next in sequence[1:]:... tally = function(tally, next)... return tally...>>> myreduce((lambda x, y: x + y), [1, 2, 3, 4, 5])15>>> myreduce((lambda x, y: x * y), [1, 2, 3, 4, 5])120If this has sparked your interest, also see the built-in operator module, which providesfunctions that correspond to built-in expressions, and so comes in handy forsome uses of functional tools:>>> import operator>>> reduce(operator.add, [2, 4, 6]) # Function-based +12>>> reduce((lambda x, y: x + y), [2, 4, 6])12354 | Chapter 17: Advanced Function Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!