当前位置:网站首页>From functools import reduce -- see the use of reduce function from typical examples

From functools import reduce -- see the use of reduce function from typical examples

2022-07-04 00:23:00 irrationality

from functools import reduce

1. Accumulation of integers : The integers in the list are accumulated

a=[1,3,5]
b=reduce(lambda x,y:x+y,a)
print('1. The integers in the list are accumulated ==:',b)
1. The integers in the list are accumulated ==: 9

2. Accumulation of lists : The lists in the list add up

a=[[1,3,5],[6]]
b=reduce(lambda x,y:x+y,a)
print('2. The lists in the list add up —:',b)
2. The lists in the list add up —: [1, 3, 5, 6]

a=[[["abc","123"],["def","456"],["ghi","789"]]]
b=reduce(lambda x,y:x+y , a )
print(' The lists in the list add up —:',b)
 The lists in the list add up —: [['abc', '123'], ['def', '456'], ['ghi', '789']]

3. Accumulation of tuples : The tuples in the list are added

a=[("abc","123"),("def","456"),("ghi","789")]
b=reduce(lambda x,y:x+y , a )
print('3. The tuples in the list are added !!',b)
3. The tuples in the list are added !! ('abc', '123', 'def', '456', 'ghi', '789')

4. Accumulation of strings

a=['abc','def','hij']
b=reduce(lambda x,y:x+y,a)
print('4. Accumulation of strings in the list :~~',b)
4. Accumulation of strings in the list :~~ abcdefhij

a=('abc','def','hij')
b=reduce(lambda x,y:x+y,a)
print(' The accumulation of strings in Yuanzu :~~',b)
 The accumulation of strings in Yuanzu :~~ abcdefhij

a=[['abc','def','hij']]
b=reduce(lambda x,y:x+y,a)
print(' The accumulation of strings in the nested list :~~',b)
 The accumulation of strings in the nested list :~~ ['abc', 'def', 'hij']

# summary :
#1.functools function ;reduce decompose ;lambda Anonymous functions ;x,y:x+y expression
#2. Use functools.reduce, If it's an integer, add up ;
#3. Use functools.reduce, If string 、 list 、 Yuanzu joined together ( Quite took off a layer of coat )

原网站

版权声明
本文为[irrationality]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202142019480672.html