题目一:
有两个列表,分别存放来老男孩报名学习linux和python课程的学生名字
linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']
python=['dragon','钢弹','zhejiangF4','小虎比']
问题一:得出既报名linux又报名python的学生列表
#常规写法:
linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']
python=['dragon','钢弹','zhejiangF4','小虎比']
l=[]
for i in linux:
for j in python:
if i==j:
l.append(i)
print(l)
---->['钢弹', '小虎比']
#列表生成式写法
linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']
python=['dragon','钢弹','zhejiangF4','小虎比']
l=[j for i in linux for j in python if i==j]
print(l)
---->['钢弹', '小虎比']
问题二:得出只报名linux,而没有报名python的学生列表
#常规写法
linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']
python=['dragon','钢弹','zhejiangF4','小虎比']
l=[]
for i in linux:
if i not in python:
l.append(i)
print(l)
---->['小壁虎', 'alex', 'wupeiqi', 'yuanhao']
#列表生成式写法
linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']
python=['dragon','钢弹','zhejiangF4','小虎比']
l=[i for i in linux if i not in python]
print(l)
---->['小壁虎', 'alex', 'wupeiqi', 'yuanhao']
问题三:得出只报名python,而没有报名linux的学生列表
linux=['钢弹','小壁虎','小虎比','alex','wupeiqi','yuanhao']
python=['dragon','钢弹','zhejiangF4','小虎比']
l=[i for i in python if i not in linux]
print(l)
----->['dragon', 'zhejiangF4']
题目二:
shares={
'IBM':36.6,
'lenovo':27.3,
'huawei':40.3,
'oldboy':3.2,
'ocean':20.1
}
问题一:得出股票价格大于30的股票名字列表
#常规写法
l=[]
for i in shares:
if shares[i] > 30:
l.append(i)
print(l)
---->['IBM', 'huawei']
#列表表达式写法
l=[i for i in shares if shares[i] > 30]
print(l)
---->['IBM', 'huawei']
问题二:求出所有股票的总价格
l=[shares[i] for i in shares]
print(sum(l))
---->127.5
题目三:
l=[10,2,3,4,5,6,7]
得到一个新列表l1,新列表中每个元素是l中对应每个元素值的平方
过滤出l1中大于40的值,然后求和
#列表写法
l=[10,2,3,4,5,6,7]
l1=[i**2 for i in l]
print(l1)
---->[100, 4, 9, 16, 25, 36, 49]
l2=[j for j in l1 if j >40]
print(l2)
----->[100, 49]
print(sum(l2))
----->149