zoukankan      html  css  js  c++  java
  • map,reduce函数练习


    1,用map来处理字符串列表啊,把列表中所有人都变成sb,比方alex_sb
    name=['alex','wupeiqi','yuanhao']
    name = list(map(lambda str1:str1 + "sb",name))
    print(name) #['alexsb', 'wupeiqisb', 'yuanhaosb']
    2,用map来处理下述l,然后用list得到一个新的列表,列表中每个人的名字都是sb结尾
    l = [{'name':'alex'},{'name':'y'}]
    new_l = map(lambda d:d["name"] + "sb",l)
    p = map(lambda  d:d,l)
    t = map(lambda  d:{'name':d["name"]+"sb"},l )
    print(list(t)) #[{'name': 'alexsb'}, {'name': 'ysb'}]
    3,用filter来处理,得到股票价格大于20的股票名字
    shares={
        'IBM':36.6,
        'Lenovo':23.2,
        'oldboy':21.2,
        'ocean':10.2,
    }
    
    f = filter(lambda x:x[-1] > 20,shares.items())
    for i in f:
        print(i[0])
    # oldboy
    # Lenovo
    # IBM

    4,
    如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格
    a.:map来得出一个包含数字的迭代器,数字指的是:购买每支股票的总价格
    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'AAPL', 'shares': 50, 'price': 543.22},
        {'name': 'FB', 'shares': 200, 'price': 21.09},
        {'name': 'HPQ', 'shares': 35, 'price': 31.75},
        {'name': 'YHOO', 'shares': 45, 'price': 16.35},
        {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    
    from functools  import  reduce
    m = map(lambda  d:d["shares"]*float(d["price"]),portfolio)
    o = list(m)
    t = map(lambda  d:d['name'],portfolio)
    print(dict(zip(t,o)))
    #{'HPQ': 1111.25, 'FB': 4218.0, 'ACME': 8673.75, 'AAPL': 27161.0, 'YHOO': 735.7500000000001, 'IBM': 9110.0}
    b,基于1的结果,用reduce来计算,购买这些股票总共花了多少钱
    print(reduce(lambda x,y:x+y ,o))# 51009.75
    c.用filter过滤出,单价大于100的股票有哪些
    m = filter(lambda  d:d["price"]> 100,portfolio)
    for i in m:
        print(i)
    # {'price': 543.22, 'name': 'AAPL', 'shares': 50}
    # {'price': 115.65, 'name': 'ACME', 'shares': 75}
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  • 相关阅读:
    oracle 数据库服务名怎么查
    vmware vsphere 6.5
    vSphere虚拟化之ESXi的安装及部署
    ArcMap中无法添加ArcGIS Online底图的诊断方法
    ArcGIS中字段计算器(高级计算VBScript、Python)
    Bad habits : Putting NOLOCK everywhere
    Understanding the Impact of NOLOCK and WITH NOLOCK Table Hints in SQL Server
    with(nolock) or (nolock)
    What is “with (nolock)” in SQL Server?
    Changing SQL Server Collation After Installation
  • 原文地址:https://www.cnblogs.com/hongyongshang/p/6705912.html
Copyright © 2011-2022 走看看