適當的使用reduce 能夠代替for循環,讓代碼更優雅
# -*- coding: utf-8 -*-
"""
(C) Guangcai Ren <[email protected]>
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) # 相當於((1-2)-3)
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