zoukankan      html  css  js  c++  java
  • python 练习用python六剑客实现一个统计数字的个数,六剑客:(map、lambda、reduce、filter、切片、推到列表)

    统计一共有几个数字

    s="sdfa45ads46723"

    #lambda

    >>> filter(lambda x:x.isdigit(),list(s))

    ['4', '5', '4', '6', '7', '2', '3']

    >>> len(filter(lambda x:x.isdigit(),list(s)))

    7

    >>> reduce(lambda x,y:x+y,map(lambda x:x.isdigit(),list("sdfa45ads46723")))

    7

    >>> reduce(lambda x,y:x+y,map(lambda x:len(x),filter(lambda x:x.isdigit(),[i for i in s][::-1])))

    7

    列表的切片还是列表,如果取一个元素就是元素本身类型

    >>> a=[1,2]

    >>> a[0]

    1

    >>> a[0:1]

    [1]

    Map的作用

    将每个列表元素都按表达式分别运算

    Reduce()累加操作

    >>> reduce(lambda x,y:x+y,[1,2,3])

    6

    X=1,y=2

    结果3传给y

    X从第二次开始存结果

    reduce(lambda x,y:x+y+y,[1,2,3])

    x=1,y=2,y=2
    x=5,y=3,y=3
    11
    x是5就对了

    >>> reduce(lambda x,y:x+x+y,[1,2,3])

    1+1+2=4 

    4+4+3=11

  • 相关阅读:
    Map-HashMap
    Collection(List & Set)
    Redis五种数据类型详解
    Redis基本数据结构详解
    分布式Session管理
    一致性算法
    Zookeeper
    分布式锁
    线程池原理解析
    疑点难点1.1
  • 原文地址:https://www.cnblogs.com/xiaxiaoxu/p/8931586.html
Copyright © 2011-2022 走看看