python functools.reduce 代替for循环

适当的使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值