开发者学堂课程【Python 入门 2020年版:作业讲解1】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/639/detail/10319
作业讲解1
声明一个字典保存一个学生的信息,学生信息中包括:姓名、年龄、成绩(单科)、电话、性别(男、女,不明)
student ={' name ':"张三',' age ':18,' score ':98,' tel ':'1388888998',' gender ':" female '}
#声明一个列表,在列表中保存6个学生的信息(6个题1中的字典)
students =[
{' name ':'张三',' age ':18,' score ':52,' tel ':'1388888998',' gender ':' female '},
{' name ':"李四',' age ':28,' score ':89,' tel ':'1388666666',' gender ':' male '},
{' name ':'王五',' age ':21,' score ':95,' tel ':'1365588889',' gender ':' unknown '},
{' name ':' jerry ',' age ':20,' score ':9e,‘ tel ':'15666678의,' gender ':' unknown '},
{' name ':' chris ',' age ':17,' score ':98,' tel ':'13777775523',' gender ':' male '},
{' name ':' jack ',' age ':23,' score ':52,' tel ':'13999999928',' gender ':' feale '},
{' name ':' tony ',' age ':15,' score ':98,' tel ':'1388888888',' gender ':' unknown '}
]
#(1)统计不及格学生的个数
#(2)打印不及格学生的名字和对应的成绩
#(3)统计未成年学生的个数
#(4)打印手机尾号是8的学生的名字
#(5)打印最高分和对应的学生的名字
count =0
teenager _ count =0
max _ score = students [][' score ']
#假设期个学生的成绩是最高分
# max _ index =0
#假设最高分的学生下标是0
for i , student in enumerate ( students ):
if student [' score ']<60:
count +=1
print ('% s 不及格,分数是% d '%( student [' name '], student [' score ']))
if student [' age ']<18:
teenager _ count +=1
# if student [' tel ']. endswith ('8'):
if student [' tel '][-1]=='8':
print ('% s 的手机号以8结尾'% student [' name '])
if student [' score ']> max _ score :
#遍历时,发现了一个学生的成绩大于假设的最大数
max _ score = student [' score ']
# max _ index = i #修改最高分的同时,把最高分的下标也修改
print ('不及格的学生有% d 个'% count )
print ('未成年的学生有% d 个'% teenager _ count )
print ('最高成绩是% d '% max _ score )
for student in students :
if student [' score ']== max _ score :
print ('最高分是% s '% student [' name '])
# print ('最高分名字是% s '% students [ max _ index ][' name '])
#(6)删除性别不明的所有学生(这个地方有个坑,跳不出来的话大家可以在群里套路,或者等老师的解答)
#方法一,将不需要除的数据添加到新列表
new _ students =[ x for x in students if x [' gender ']!=' unknown '] print ( new _ students )
#方法二,使用 for 循环倒着洲除要酬除的数据,避免“坑”
i =0
for i in range ( len ( students )-1,-1,-1):
if students [ i ][' gender ']==' unknown ':
students . remove ( students [ i ])
print ( students )
#方法三,使用 while 循环删除需要删除的数据,并及时补齐因删除数据而导致的列表数据索引变化,避免漏删数据
i =0
while i < len ( students ):
if students [ i ][' gender ']==' unknown ':
students . remove ( students [ i ])
i -=1
i +=1
print ( students )
#方法四,遍历在新的列表操作,刷除是在原来的列表操作( students [:]是 studens 的切片,所以修改 students 对切片无影响)
i =0
for student in students [:]:
if student [' gender ']==' unknown ':
students . remove ( student )
print ( students )
#方法五,使用内建函数 filter ()和匿名函数
new _ students = filter (1ambda x : x [' gender ']!=' unknown ', students )
print ( list ( new _ students ))
print ('-----------------')
#(7)将列表按学生成绩从大到小排序(选做)
for jin range (0, len ( students )-1):
for i in range (0, len ( students )-1- j ):
if students [ i ][' score ']< students [ i +1][' score ']:
students [ i ], students [ i +1]= students [ i +1], students [ i ]
print ( students )