首页 > 代码库 > Python实操二

Python实操二

  实操一:

  1、用map来处理字符串列表啊,把列表中所有人都变成sb,比方alex_sb
    name=[‘alex‘,‘wupeiqi‘,‘yuanhao‘]

name=[‘alex‘,‘wupeiqi‘,‘yuanhao‘]
m = map(lambda name:name+"_SB",name)
print(list(m))
------------输出结果------------------
[‘alex_SB‘, ‘wupeiqi_SB‘, ‘yuanhao_SB‘]

  2、用map来处理下述l,然后用list得到一个新的列表,列表中每个人的名字都是sb结尾

  l=[{‘name‘:‘alex‘},{‘name‘:‘egon‘}]

l=[{‘name‘:‘alex‘},{‘name‘:‘egon‘}]
m = map(lambda l : l["name"]+"_SB",l)
print(list(m))
----------输出结果-----------
[‘alex_SB‘, ‘egon_SB‘]

  实操二:

  用filter来处理,得到股票价格大于20的股票名字

    shares={
        ‘IBM‘:36.6,
        ‘Lenovo‘:23.2,
        ‘oldboy‘:21.2,
        ‘ocean‘:10.2,
        }

f = filter(lambda d:shares[d]>20,shares)
for i in f:
    print(i)
----------输出结果------------
IBM
Lenovo
oldboy

  实操三:

  如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格
  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}
        ]

  1、map来得出一个包含数字的迭代器,数字指的是:购买每支股票的总价格

m = map(lambda d:d["shares"]*d["price"],portfolio)
l1 = list(m)
print(l1)
--------------输出结果---------------
[9110.0, 27161.0, 4218.0, 1111.25, 735.7500000000001, 8673.75]

  2、基于1的结果,用reduce来计算,购买这些股票总共花了多少钱

l1=[9110.0, 27161.0, 4218.0, 1111.25, 735.7500000000001, 8673.75]
print(reduce(lambda x,y:x+y,l1))
--------------输出结果------------------
51009.75

  3、用filter过滤出,单价大于100的股票有哪些

f = filter(lambda d:d["price"]>=100,portfolio)
l2 = list(f)
print(l2)
-----------------------输出结果-----------------------------
[{‘name‘: ‘AAPL‘, ‘shares‘: 50, ‘price‘: 543.22}, {‘name‘: ‘ACME‘, ‘shares‘: 75, ‘price‘: 115.65}]

  

 

Python实操二