[Python] reduce() function

The reduce() function will accumulate the elements in the parameter sequence

Grammatical structures

reduce(function, iterable[, initializer])

Parameter Description

function : function, with two parameters

iterable : iterable object

initializer : initial parameter (optional)

return value

Returns the function evaluation result

To sum up, the reduce() function performs the following operations on all the data in a data set. First, take out 2 elements from the data set to execute the specified function function, and pass the output result and the third element into the function function, and output The result is then passed to the function function with the fourth element for calculation, and so on, until every element in the list is exhausted for accumulation, and finally the calculation result is returned

Tips

In python3, there is no reduce() function in the built-in function, it is now placed in the functools module, if you want to use it, you need to call the reduce() function by introducing the functools module

from functools import reduce

Example 1

from functools import reduce

# 两数相加
def add(x,y):
    return x + y

# 计算1 + 2 + 3 + ... + 100的和
sum1 = reduce(add, range(1, 101))  
print(sum1)  # 5050

# 计算列表和:1+2+3+4+5
# 使用lambda匿名函数+reduce()函数
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])
print(sum2)  # 15

sum3 = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 6)
# 21 = 6 + 1 + 2 + 3 + 4 + 5 
print(sum3)  # 21

Example 2

from functools import reduce
lst = [1,2,3,4,5]
# 120 = 1 * 2 * 3 * 4 * 5
print(reduce(lambda x,y:x*y,lst))  # 120

Example 3

from functools import reduce

str1="abcdefg"

# gfedcba
print(reduce(lambda x,y:y+x, str1))

Example 4

from functools import reduce

sentences = ['Hello World!! hello Andy'] 

# 统计字符串'Hello'出现的次数
word_count =reduce(lambda a,x:a+x.count("Hello"), sentences, 0)
print(word_count)  # 1

Guess you like

Origin blog.csdn.net/Hudas/article/details/130730138