编程语言
首页 > 编程语言> > 025_Python3 reduce 函数高级用法

025_Python3 reduce 函数高级用法

作者:互联网

# -*- coding: UTF-8 -*-

'''
用法:reduce (func, seq[, init()])
    参数1:function句柄,用于完成迭代对象中两个元素之间的操作
    参数2:迭代对象

功能:
    reduce函数用途:对迭代对象中的元素从左至右两两送入参数1传入的function中进行运算
'''

from functools import reduce

# 1. 求和
s = sum([i for i in range(101)])
print(s)  # 5050

s1 = reduce(lambda x, y: x + y, range(101))
print(s1)  # 5050

# 2. 元组对象求和
scientists = ({'name': 'Alan Turing', 'age': 105, 'gender': 'male'},
              {'name': 'Dennis Ritchie', 'age': 76, 'gender': 'male'},
              {'name': 'Ada Lovelace', 'age': 202, 'gender': 'female'},
              {'name': 'Frances E. Allen', 'age': 84, 'gender': 'female'})


def reducer(accumulator, value):
    s = accumulator + value['age']
    # 注意 第二次循环执行时,reducer 会变成sum,即数字,
    # 所以下面必须给一个初始值 0
    return s


total_age = reduce(reducer, scientists, 0)
print(total_age)  # 467
# 酱紫也可以
print(sum([x['age'] for x in scientists]))  # 467
print(reduce(lambda x, y: x + y, range(1, 101), 2))  # 5052

# 3. 列表合并
lst = [
    [1, 2, 3],
    [4, 5],
    [6, 7, 8],
    [9, 10, 11, 12]
]

print(reduce(lambda x, y: x + y, lst))  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


# 4. [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5],统计这个集合所有键的重复个数,返回字典
def statistics(dic, k):
    if not k in dic:
        dic[k] = 1
    else:
        dic[k] += 1
    return dic


lst = [1, 1, 2, 3, 2, 3, 3, 5, 6, 7, 7, 6, 5, 5, 5]
print(reduce(statistics, lst, {}))  # {1: 2, 2: 2, 3: 3, 5: 4, 6: 2, 7: 2}
# 也就是说 reduce的第一个参数是一个 func,该 func 的第一个参数是 reduce 的第三个参数,
# 第二个参数是 reduce 的第二个参数(里面的每一项)

 

标签:age,reduce,dic,025,lst,参数,print,Python3
来源: https://www.cnblogs.com/luwei0915/p/14612105.html