python_函数部分

总结:内置函数(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',

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值