Here’s the official explanation: Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

Format: Creduce (func, seq[, init()])

The reduce() function is a reduction function, and its execution process is as follows: for each iteration, the result of the previous iteration (note: the first is the init element, if init is not specified, the first element of seq) is passed into the binary func function for execution along with the next element. In reduce(), init is optional and is used as the first element of the first iteration if specified, or the first element in seq if not specified.

For example,

Have a set sequence, such as,1,2,3,2,3,3,5,6,7,7,6,5,5,5 [1], the statistical number of repeat this collection all keys 1 appeared twice, for example, 2 appeared twice, etc. The idea is to use a dictionary, where the element is the dictionary key, and the number of occurrences is the dictionary value. There are many ways to do this. The first one is for loop judgment

def statistics(lst): 
  dic = {} 
  for k in lst: 
    if not k in 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(statistics(lst)) 
Copy the code

Second: the comparison of cheating, the first list with set to heavy, and then use the list of count method

def statistics2(lst): 
  m = set(lst) 
  dic = {} 
  for x in m: 
    dic[x] = lst.count(x) 
  return dic
lst = [1.1.2.3.2.3.3.5.6.7.7.6.5.5.5] 
print statistics2(lst) 
Copy the code

The third way is to use reduce

def statistics(dic,k):
  if not k in 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.5Print reduce(statistics, LST,{}) print reduce(statistics, LST,{}) D = {} d.xtend (LST) print reduce(statistics,d) # As the first argument to statistics, the traversal collection in turn takes the second argumentCopy the code

Through the above examples, it can be found that all the problems that need to be operated on a set and have a statistical result and can be solved in a circular or recursive way can be realized by reduce in general.