基于列表生成式
linux = [‘钢弹‘,‘小壁虎‘,‘小虎比‘,‘alex‘,‘wupeiqi‘,‘yuanhao‘]
python = [‘dragon‘,‘钢弹‘,‘zhejiangF4‘,‘小虎比‘]
一:得出既报名linux又报名python的学生列表
p_some_l = [] p_some_l = [p_python for x_linux in linux for p_python in python if x_linux == p_python] print(p_some_l) #[‘钢弹‘, ‘小虎比‘]
二:得出只报名linux,而没有报名python的学生列表
1 l_not_py = [x_linux for x_linux in linux if x_linux not in python] 2 print(l_not_py)#[‘小壁虎‘, ‘alex‘, ‘wupeiqi‘, ‘yuanhao‘]
三:得出只报名python,而没有报名linux的学生
py_no_l = [p_python for p_python in python if p_python not in linux] print(py_no_l) # [‘dragon‘, ‘zhejiangF4‘]
列表 l=[10,2,3,4,5,6,7]
1、得到一个新列表l1,新列表中每个元素是l中对应每个元素值的平方
l = [10,2,3,4,5,6,7] l1= [x * x for x in l ] #把迭代对象迭代并返回自乘方的一个新列表 tmp = [x for x in l1 if x > 40] # [100, 49] #筛选出大于40的值 print(tmp) print (l1) #[100, 4, 9, 16, 25, 36, 49]
2、过滤出l1中大于40的值,然后求和
print(sum(tmp)) #149 #对刚才使用者产生的新表【100,49】求和
一:得出股票价格大于30的股票名字列表
shares={ ‘IBM‘:36.6, ‘lenovo‘:27.3, ‘huawei‘:40.3, ‘oldboy‘:3.2, ‘ocean‘:20.1 } dicg = ((i,v) for i ,v in shares.items()) #定制生成器 P = [i[0] for i in dicg if float(i[-1]) > 30] # [‘huawei‘, ‘lenovo‘, ‘oldboy‘, ‘IBM‘, ‘ocean‘] print(P) # [‘IBM‘, ‘huawei‘]
二:求出所有股票的总价格
dicg = ((i,v) for i ,v in shares.items()) P_price = (i[-1] for i in dicg) print(sum(P_price)) #127.5
时间: 2024-09-30 00:16:53