The use of reduce built-in functions in Python guide _python

Source: Internet
Author: User
Tags iterable in python

Official explanation:

Apply function of two arguments cumulatively to the ' items of iterable, from left to right, so as to reduce the iterable to A single value. For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates ((((1+2) +3) +4). The left argument, X, are the accumulated value and the right argument, y, are the update value from the iterable. If the optional initializer is present, it's placed before the items of the iterable in the calculation, and serves as a Default when the iterable is empty. If initializer is isn't given and Iterable contains only one item, the ' the ' is returned. Roughly equivalent to:

This means that an iterative object can be applied to a method with two parameters, which we call Appfun, traversing the iterated object, taking the elements in turn as Appfun parameters, but this function has two parameters, which argument? There is such a rule, look at the following implementation of the reduce method, there are three parameters, the first parameter is the appfun mentioned above, the second parameter is the iteration of the object, and the third? When the reduce method is invoked, the initializer parameter is given, so the first time the appfun is called, the parameter value is used as the first parameter, and the elements of the iteration object are followed by the second argument of Appfun. If the call to reduce does not give initializer this parameter, then the first time the Appfun is invoked, the first element of the object can be iterated as the first element of the Appfun, and the iterator's second element from the second to the last, in turn, as the Appfun, In addition to the first call, the first parameter of the Appfun is the return value of the Appfun. For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]), computes 1 to 5 and, because there is no given initializer parameter, so the first call to X+y, X=1, that is, the first element of the list, the y=2, the second element of the list, and then the return of 1 The result of +2 as a second call to the X in X+y, the last result, the y=2, the second element, and so on, to know the result of the 1+2+3+4+5.

So, in fact, the following code definition is a bit of a problem, we call this code in the program reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]), the result is 16, and the correct result is 15, the problem is if the set does not start with 0, follow the following code, The first call to X=1, the first element, Y is equal to 1, and the first element, and the correct y should be 2. So the real reduce method should be different from the example below.

def reduce (function, iterable, initializer=none): 
  it = iter (iterable) 
  if initializer is None: 
    try: 
      initializer = next (it) 
    except stopiteration: 
      raise TypeError (' reduce () of empty sequence with no initial value ') C7/>accum_value = initializer 
  for x in iterable: 
    accum_value = function (Accum_value, x) return 
  Accum_value 

So what can the reduce function do, and in what case reduce it, look at the following example:

For example, in the above example, to achieve an accumulation of a set of plastic. Suppose LST = [1,2,3,4,5], there are many ways to accumulate:

First: Use the SUM function .

 
 


The second kind: the circulation way.

def customer_sum (LST): result 
  = 0 for 
  x in LST: result+=x return result 
 
#或者 
def customer_sum ( LST): Result 
  = 0 while 
  lst: 
      temp = lst.pop (0) 
      result+=temp return result 
 
if __name__== "__ main__ ": 
  lst = [1,2,3,4,5] 
  print customer_sum (LST) 

The third type: recursive summation

def add (lst,result): 
  if lst: 
    temp = lst.pop (0) 
    Temp+=result return 
    Add (lst,temp) 
  else: Return result 
 
if __name__== "__main__": 
  lst = [1,2,3,4,5] 
  print Add (lst,0) 

Type Fourth: Reduce mode

LST = [1,2,3,4,5] 
print reduce (lambda x,y:x+y,lst) 
#这种方式用lambda表示当做参数 because the third parameter of reduce is not provided, so the first time the execution is x=1,y=2, The second x=1+2,y=3, which is the third element of the list 
 
 
#或者 
lst = [1,2,3,4,5] 
print reduce (lambda x,y:x+y,lst,0) 
#这种方式用lambda表示当做参数 Because the third parameter of reduce is specified as 0, so the first execution X=0,y=1, the second x=0+1,y=2, the second element of the list, assuming that the 
third parameter of reduce is 100, then the first execution x=100,y is still the element that traverses the list , the final result is the 
 
 
 
#或者 
def Add (x,y): return 
  x+y 
 
print reduce (add, LST) 
#与方式1相同, Just replaced the lambda expression with a custom function 
 
#或者 
def Add (x,y): return 
  x+y 
 
print reduce (add, lst,0) 


One more example: There is a sequence set, for example [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5], that counts the number of repetitions of all the keys in this set, for example 1 appears two times, 2 appears two times, and so on. The general idea is to use the dictionary storage, the element is the key of the dictionary, the number of occurrences is the value of the dictionary. There are still many ways

The first kind: For loop judgment

def statistics (LST): 
  dic = {} for 
  K in LST: 
    if not k in dic: 
      dic[k] = 1 
    else: 
      dic[k] +=1 
  retur n dic 
 
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5] 
print (statistics (LST)) 

The second: The more tricky, first the list with set way to weight, and then use the list of the Count method

def STATISTICS2 (LST): 
  m = set (LST) 
  dic = {} for 
  x in M: 
    dic[x] = lst.count (x) return 
 
  dic 
 
ls t = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5] 
print STATISTICS2 (LST) 

The third: Use reduce method

def statistics (DIC,K): 
  if not k on dic: 
    dic[k] = 1 
  else: 
    dic[k] +=1 return 
  dic 
 
lst = [1,1,2,3,2,3 , 3,5,6,7,7,6,5,5,5] 
print reduce (statistics,lst,{})  
#提供第三个参数, for the first time, the initial dictionary is empty, as the first parameter of statistics, and then traversing LST, As the second argument, and then the returned dictionary collection is the next first argument or the 
d = {} 
d.extend (LST) 
print reduce (statistics,d) 
# Does not provide a third parameter, but to ensure that the first element of the collection is a Dictionary object, as the first argument of the statistics, iterate through the collection as the second argument 

The above example shows that any problem that is to be manipulated on a set and has a statistical result that can be solved by loop or recursion can generally be done in reduce mode.

The reduce function is really "a good comrade"!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.