美文网首页
匿名函数4(实战)

匿名函数4(实战)

作者: 闲云野鹤_23dd | 来源:发表于2020-12-28 10:45 被阅读0次

匿名函数4(实战)

reduce

reduce() 函数会对参数序列中元素进行累积。

将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
语法:

reduce(function, 列表/元组等可迭代对象)

例子:

from functools import reduce

v1 = ['wo','hao','e']
v2 = [1,2,3]
def func(x,y):
    return x+y

def redus_demo():
    r1 = reduce(func, v1)
    print(r1)  # wohaoe

r2 = reduce(lambda x,y:x+y,v1)
print(r2)   # wohaoe

def redus_demo2():
  r3 = reduce(lambda x, y: x + y, v2)
  print(r3)

r4 = reduce(lambda x, y: x * y, v2)
print(r4)` 

def redus_demo3():
  # 计算0到100的和
  print( reduce(lambda x, y: x + y, range(101)) )` 

filter

按条件过滤,将元素在方法中执行,返回结果为True的保留下来。
返回的结果是 filter 对象, 可以使用list函数转换成list对象

语法:

filter(function, 数据)

例子:

def f1():
    # 求大于2的元素
    result=filter(lambda x:x > 2,[1,2,3,4])
    print(type(result))
    print(list(result))

求列表中的数字

v3 = [11,22,33,'asd',44,'xf']
def fun1(i):
    if type(i) == int:
        return True
    return False
def f2():
    result = filter(fun1, v3)
    print(list(result))  # [11,22,33,44]
    # 简化做法
    result = filter(lambda x: True if type(x) == int else False, v3)
    print(list(result))` 

求列表中的 偶数

def f3():
     result = filter(lambda x: True if type(x) == int and x%2==0 else False, v3)
    print(list(result))` 

更简单的写法

 def f4():
        # 求列表中的数字
        print(list( filter(lambda x: type(x) == int, v3) ))

#求列表中的 偶数
print(list( filter(lambda x: type(x) == int and x%2==0, v3) ))` 

字典过滤

def f5():
    salaries = {
    'egon': 3000,
    'alex': 100000000,
    'wupeiqi': 10000,
    'yuanhao': 2000
}
## 大于10000的键值对
    res = filter(lambda k: salaries[k] >= 10000, salaries)
    print(list(res))

  info = [
    {'name': 'egon', 'age': '18', 'salary': '3000'},
    {'name': 'wxx', 'age': '28', 'salary': '1000'},
    {'name': 'lxx', 'age': '38', 'salary': '2000'}
]
## 工资大于1000 的字典
res2 = filter(lambda x: int(x['salary'])>1000,info)
print(list(res2))

相关文章

  • 匿名函数4(实战)

    匿名函数4(实战) reduce reduce() 函数会对参数序列中元素进行累积。 将一个数据集合(链表,元组等...

  • 匿名函数3(实战)

    匿名函数3(实战) 接下来学习 : max,min,sorted,map,reduce,filter .这些函数可...

  • 10 Go匿名函数 && 闭包

    1、函数的基本规则 2、函数的参数 3、什么是匿名函数 4、匿名函数的应用 4.1 4.2 4.3、 5 闭包

  • 【第66天】python全栈从放弃入门到放弃

    1 函数 定义普通的函数 定义匿名函数 自执行函数 2 使用匿名函数遍历js数组中的元素 3 函数的返回值 4 调...

  • day11高级函数和变量的作用域

    1. 匿名函数 1.1 什么是匿名函数 没有函数名的函数就是匿名函数 (匿名函数还是函数!!!!!!) 1.2 ...

  • Block用法

    概述 block:苹果在iOS4开始引入的对C语言的扩展,用来实现匿名函数的特性。匿名函数:没有函数名的函数,一对...

  • Block分析

    2017/4/11 Block:带有自动变量(局部变量)的匿名函数 声明一个匿名函数int func(int co...

  • Day10-匿名函数&变量的作用域&函数递归&迭代器&生成器

    匿名函数 1.匿名函数 匿名函数就是没有函数名的函数; 匿名函数可以看成是类型是function的值和10, 'a...

  • Day10 函数

    一.匿名函数 1.匿名函数 匿名函数就是没有函数名的函数; 匿名函数可以看成是类型是function的值和10, ...

  • select的常见用法

    原文:《go并发编程实战》 select 常与匿名函数连用,以便不阻塞主程序。 select 常与for循环连用,...

网友评论

      本文标题:匿名函数4(实战)

      本文链接:https://www.haomeiwen.com/subject/fafanktx.html