Guide to Using reduce built-in functions in python, pythonreduce

Source: Internet
Author: User
Tags iterable

Guide to Using reduce built-in functions in python, pythonreduce

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)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to:

That is to say: Apply an iteratable object to a method with two parameters. We call it appFun. traverse this iteratable object and use the elements in it as appFun parameters in sequence, but this function has two parameters. Which one is used as the parameter? There is such a rule. Looking at the implementation of the reduce method in the lower layer, there are three parameters. The first parameter is the appFun mentioned above, and the second parameter is the iteratable object, what about the third? If the initializer parameter is provided when the reduce method is called, the value of this parameter is used as the first parameter when appFun is called for the first time, the elements of the iteratable object are used as the second parameter of appFun. If the initializer parameter is not provided when reduce is called, when appFun is called for the first time, the first element of an iteratable object is the first element of appFun, And the iterator starts from the second element to the last one as the second parameter of appFun. Except for the first call, the first parameter of appFun is the return value of appFun. For example, reduce (lambda x, y: x + y, [1, 2, 3, 4, 5]) calculates the sum between 1 and 5, because the initializer parameter is not given, so when we call x + y for the first time, x = 1, that is, the first element of the list, y = 2, that is, the second element of the list, then the result of 1 + 2 is returned as x in the second call of x + y, that is, the result of the previous call, y = 2, that is, the second element, and so on, the result is 1 + 2 + 3 + 4 + 5.

In this case, the following code definition is actually 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 that if the set does not start with 0, then follow the code below to call x = 1 for the first time, that is, the first element, y is equal to 1, is also the first element, and the correct y should be 2. So the real reduce method should be different from the following example.

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')   accum_value = initializer   for x in iterable:     accum_value = function(accum_value, x)   return accum_value 

So what can reduce function do and when reduce is used? Let's look at the example below:

For example, in the above example, we can accumulate an integer set. Assume that the lst is [1, 2, 3, 4, 5]. There are many ways to accumulate:

First: Use the sum function.

sum(lst) 

 
Type 2: loop mode.

Def customer_sum (lst): result = 0 for x in lst: result + = x return result # Or 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)

Third: 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) 

Fourth: reduce Mode

Lst = [1, 2, 3, 4, 5] print reduce (lambda x, y: x + y, lst) # This method is represented as a parameter using lambda, because the third parameter of reduce is not provided, x = 1, y = 2, x = 1 + 2, y = 3, that is, the third element of the list # Or lst = [1, 2, 3, 4, 5] print reduce (lambda x, y: x + y, lst, 0) # This method uses lambda as a parameter. Because the third parameter of reduce is specified as 0, x = 0, y = 1, and x = 0 + 1 for the first execution, y = 2, that is, the second element of the list. If the third parameter of reduce is 100, x = 100 is executed for the first time, and y is still the element of the List traversal, the final result is 115 # Or def add (x, y): return x + y print reduce (add, lst) # Same as method 1, except that the lambda expression is replaced with a custom function # Or def add (x, y): return x + y print reduce (add, lst, 0) # is the same as method 2, just replace the lambda expression with a UDF.

 
For another example, there is a sequence set, such as [,], which counts the number of duplicates of all keys in the set, for example, 1 appears twice, and 2 appears twice. The general idea is to store data in a dictionary. The element is the dictionary key and the number of occurrences is the dictionary value. There are still many methods

First: 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)) 

The second method: the list is de-duplicated by using the set method, and then the count method of the List is used.

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) 

Third: reduce

Def statistics (dic, k): if not k in dic: dic [k] = 1 else: dic [k] + = 1 return dic lst =, 3, 5, 6, 7, 7, 6, 5, 5] print reduce (statistics, lst, {}) # provides the third parameter. For the first time, the initial dictionary is empty and serves as the first parameter of statistics, then traverse the lst as the second parameter, and then use the returned dictionary set as the first parameter of the next time or d = {} d. extend (lst) print reduce (statistics, d) # The third parameter is not provided, but the first element of the set must be a dictionary object, which is the first parameter of statistics, the traversal set is used as the second parameter in turn.

The above example shows that any problem that requires operations on a set and statistical results can be solved in a loop or recursive manner, generally, reduce can be used.

The reduce function is really a good comrade "!


Python built-in functions

I am also learning python. How can I discuss it together?

Python reduce ()

''. Join (map (lambda x: x. capitalize (), [" emperor "," joshua "," abraham "," norton "])

Related Article

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.