适当的使用reduce 能够代替for循环,让代码更优雅
# -*- coding: utf-8 -*-
"""
(C) rgc
All rights reserved
create time '2020/3/23 19:01'
Module usage:
一个迭代器(叫累加器容易引起误会,误认为只能累加),第一个和第二个进行操作,并把结果第三个操作。。。,直到序列的元素只有一个为止;
如:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
相当于:((((1+2)+3)+4)+5)
用途:更优雅的写代码
#1.functools函数;reduce分解;lambda 匿名函数;x,y:x+y 表达式
#2.使用functools.reduce,要是整数就累加;
#3.使用functools.reduce,要是字符串、列表、元祖就拼接(相当脱了一层外套)
"""
from functools import reduce
a = [3, 2, -1]
res = reduce(lambda x, y: x + y, a) # 相当于((3+2)+(-1))
print('使用reduce的结果', res) # 使用reduce的结果 4
res_count = 0
for item in a:
res_count += item
print('使用for循环的结果', res_count) # 使用for循环的结果 4
print('总结:当然使用 reduce 写代码喽!')
print('reduce其他使用方式')
a = ['a', 'b', 'c']
res = reduce(lambda x, y: x + y, a)
print('字符串拼接', res) # 字符串拼接 abc
a = [['a'], ['b'], ['c']]
res = reduce(lambda x, y: x + y, a)
print('字符串拼接', res) # 字符串拼接 ['a', 'b', 'c']
a = [['a', 'd'], ['b', 'e'], ['c']]
res = reduce(lambda x, y: x + y, a)
print('字符串拼接', res) # 字符串拼接 ['a', 'd', 'b', 'e', 'c']
a = [[["abc", "123"], ["def", "456"], ["ghi", "789"]]]
res = reduce(lambda x, y: x + y, a)
print('字符串list一次reduce', res) # 字符串list一次reduce [['abc', '123'], ['def', '456'], ['ghi', '789']]
res = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y, a))
print('字符串list两次reduce', res) # 字符串list两次reduce ['abc', '123', 'def', '456', 'ghi', '789']
相关链接:
https://blog.csdn.net/weixin_43969815/article/details/92814587