总结:内置函数(reduce,filter,sorted)
首先来说reduce函数,首先来看一看reduce函数的底层。
def reduce(function, sequence, initial=_initial_missing):
"""
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
redece(函数体,队列,初始值): reduce():对列表中的函数进行加减乘除的运算的函数,下面来看一个代码:
from functools import reduce
tuple1 = (3,4,5,6,7,8) # 定义一个元组
result = reduce(lambda x,y:x+y,tuple1) # 定义一个lambda函数,对元组进行求和。
print(result)
运行结果如下:
33
2,filter函数:
filter(函数,列表):返回对列表中判断为真的值。来看一看函数的底层。
class filter(object): """ filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. """
filter(函数块,可迭代的对象)。来看一看代码:
# 过滤列表里面所有大于10的,filter(),lambda是一种函数规范,规定某个函数应该怎么写,
# filter(函数,列表):返回对列表中判断为真的值。
list2 = [2,3,4,5,12,677,67,3,543]
result = filter(lambda x:x > 10,list2)
print(list(result))
运行结果如下:
[12, 677, 67, 543]
3,sorted函数:
# 找出所有年龄大于20岁的学生
students = [
{'name':'tony','age':20},
{'name':'lucy','age':19},
{'name':'lily','age':13},
{'name':'mark','age':21},
{'name':'jack','age':23},
{'name':'steven','age':18}
]
result = filter(lambda x:x['age'] > 20,students)
# print(result)
print(list(result))
# 排序:按照年龄从小到大进行排序:
result = sorted(students,key=lambda x:x['age'])
print(result)
运行结果:
[{'name': 'lily', 'age': 13}, {'name': 'steven', 'age': 18}, {'name': 'lucy', 'age': 19}, {'name': 'tony',