Python实操

  有两个列表,分别存放报名学习linux和python课程的学生名字

    linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']

    python=['dragon','钢弹','zhejiangF4','小虎比']

  问题一:得出既报名linux又报名python的学生列表

l1 = [i for i in linux if i in python ]
print(l1)
-------输出结果-------
['钢弹', '小虎比']

  问题二:得出只报名linux,而没有报名python的学生列表

l1 = [i for i in linux if i not in python]
print(l1)
----------------输出结果------------------
['小壁虎', 'alex', 'wupeiqi', 'yuanhao']

  问题三:得出只报名python,而没有报名linux的学生列表

l1 = [i for i in python if i not in linux]
print(l1)
---------输出结果---------
['dragon', 'zhejiangF4']

  shares={ 'IBM':36.6, 'lenovo':27.3, 'huawei':40.3, 'oldboy':3.2, 'ocean':20.1 }

  问题一:得出股票价格大于30的股票名字列表

list = [i for i in shares if shares[i] > 30]
print(list)
----------输出结果---------
['IBM', 'huawei']

  另一方法:

print([i for i,j in shares.items() if j > 30])
-----------------输出结果----------------------
    ['IBM', 'huawei']

 问题二:求出所有股票的总价格

list = [shares[i] for i in shares] #把字典所有的values,转成一个列表
print(sum(list)) #打印列表的总和
print(sum([shares[i] for i in shares]) #简写形式
-------输出结果--------
    127.5

  另一种方法:

print(sum([j for i,j in shares.items()]))
------------------输出结果------------------
    127.5

  l=[10,2,3,4,5,6,7] 得到一个新列表l1,新列表中每个元素是l中对应每个元素值的平方 过滤出l1中大于40的值,然后求和

list = [i**2 for i in l if i**2 > 40] #得出取幂后大于40的值的列表
print(sum(list)) #对列表求和
print(sum[i**2 for i in l if i**2 > 40]) #简写形式
--------输出结果--------
    149

  

  

原文地址:https://www.cnblogs.com/Michael--chen/p/6701208.html