reduce()函数
Posted 小小菜_v
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了reduce()函数相关的知识,希望对你有一定的参考价值。
reduce()函数
reduce() 函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
"""
reduce 函数
"""
from functools import reduce
def add(x, y):
return x + y
if __name__ == '__main__':
list1 = [1, 2, 3]
a = reduce(add, list1)
print(a)
输出如下
C:\\Python_Practice\\venv\\Scripts\\python.exe C:/Python_Practice/reduce_demo.py
6
Process finished with exit code 0
但是如下情况则不一样
"""
reduce 函数
"""
from functools import reduce
def dict_add(x, y):
return x["age"] + y["age"]
if __name__ == '__main__':
list2 = [{"name": "Lily", "age": 11},
{"name": "Bob", "age": 15},
{"name": "Joe", "age": 18}]
b = reduce(dict_add, list2)
print(b)
输出报错
C:\\Python_Practice\\venv\\Scripts\\python.exe C:/Python_Practice/reduce_demo.py
Traceback (most recent call last):
File "C:/Python_Practice/reduce_demo.py", line 23, in <module>
b = reduce(dict_add, list2)
File "C:/Python_Practice/reduce_demo.py", line 12, in dict_add
return x["age"] + y["age"]
TypeError: 'int' object is not subscriptable
Process finished with exit code 1
由于x,y值是取list2列表中的第1,2个元素age的值,返回的是int型26赋值给下一轮的x,若再取x[“age”],则会报类型错误,所以得做如下处理,添加一个默认值:
"""
reduce 函数
"""
from functools import reduce
def add(x, y):
return x + y
def dict_add(x, y):
return x + y["age"]
if __name__ == '__main__':
# list1 = [1, 2, 3]
# a = reduce(add, list1)
# print(a)
list2 = [{"name": "Lily", "age": 11},
{"name": "Bob", "age": 15},
{"name": "Joe", "age": 18}]
b = reduce(dict_add, list2, 0)
print(b)
返回如下:
C:\\Python_Practice\\venv\\Scripts\\python.exe C:/Python_Practice/reduce_demo.py
44
Process finished with exit code 0
以上是关于reduce()函数的主要内容,如果未能解决你的问题,请参考以下文章