使用一個(gè)變量all_students保存一個(gè)班的學(xué)生信息(4個(gè)),每個(gè)學(xué)生需要保存:姓名、年齡、成績(jī)、電話(huà)
all_students = [
{'name':'stu1', 'age': 19, 'score':81, 'tel':'192222'},
{'name':'stu2', 'age': 29, 'score':90, 'tel':'211222'},
{'name':'stu3', 'age': 12, 'score':67, 'tel':'521114'},
{'name':'stu4', 'age': 30, 'score':45, 'tel':'900012'},
]
1.添加學(xué)生:輸入學(xué)生信息,將輸入的學(xué)生的信息保存到all_students中
例如輸入:
姓名: 小明
年齡: 20
成績(jī): 100
電話(huà): 111922
那么就在all_students中添加{'name':'小明', 'age': 20, 'score': 100, 'tel':'111922'}
dict_students = {}
name = input('姓名:')
age = input('年齡:')
score = input('成績(jī):')
tel = input('電話(huà):')
dict_students['name'] = name
dict_students['age'] = age
dict_students['score'] = score
dict_students['tel'] = tel
all_students.append(dict_students)
print(all_students)
結(jié)果如下:
[{'name': 'stu1', 'age': 19, 'score': 81, 'tel': '192222'},
{'name': 'stu2', 'age': 29, 'score': 90, 'tel': '211222'},
{'name': 'stu3', 'age': 12, 'score': 67, 'tel': '521114'},
{'name': 'stu4', 'age': 30, 'score': 45, 'tel': '900012'},
{'name': 'stu5', 'age': '20', 'score': '95', 'tel': '123456'}]
2.按姓名查看學(xué)生信息:
例如輸入:
姓名: stu1 就打?。?name':'stu1', 'age': 19, 'score':81, 'tel':'192222'
name_in = input('學(xué)生姓名')
for index in range(0,len(all_students)):
if all_students[index]['name'] == name_in:
print(all_students[index])
3.求所有學(xué)生的平均成績(jī)和平均年齡
sum_score = 0; sum_age = 0
for index in range(0, len(all_students)):
sum_score += all_students[index]['score']
sum_age += all_students[index]['age']
print('學(xué)生的平均成績(jī)是%.2f,平均年齡是%.2f' %((sum_score)/len(all_students), (sum_age)/len(all_students)))
結(jié)果如下:
學(xué)生的平均成績(jī)是70.75,平均年齡是22.50
。。。。。
sum_score=0
sum_age=0
for index in range(len(all_students)):
sum_score+=all_students[index]['score']
sum_age+=all_students[index]['age']
ave_score=sum_score/len(all_students)
ave_age=sum_age/len(all_students)
print("平均成績(jī)是%.2f,平均年齡是%.2f"%(ave_score,ave_age))
4.刪除班級(jí)中年齡小于18歲的學(xué)生
for index in range(0, len(all_students)):
if all_students[index]['age'] < 18:
del all_students[index]['name']
del all_students[index]['age']
del all_students[index]['score']
del all_students[index]['tel']
print(all_students)
結(jié)果如下:[{'name': 'stu1', 'age': 19, 'score': 81, 'tel': '192222'}, {'name': 'stu2', 'age': 29, 'score': 90, 'tel': '211222'}, {}, {'name': 'stu4', 'age': 30, 'score': 45, 'tel': '900012'}]
5.統(tǒng)計(jì)班級(jí)中不及格的學(xué)生的人數(shù)
count = 0
for index in range(0, len(all_students)):
if all_students[index]['score'] < 60:
count += 1
print(count)
結(jié)果如下:
1
6.打印手機(jī)號(hào)最后一位是2的學(xué)生的姓名
for index in range(len(all_students)):
student=all_students[index]
tel= int(student['tel'])
if tel %10==2:
print(student['name'])
輸出結(jié)果為:
stu1
stu2
stu4