使用一个变量all_students保存一个班的学生信息(4个),每个学生需要保存:姓名、年龄、成绩、电话
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'},
]
all_studens = []
for x in range(1,5):
new_name = input('请输入第%位学生姓名:' % x)
new_age = int(input('请输入第%位学生年龄:'% x))
new_score = int(input('请输入第%位学生成绩:'% x))
new_tel = int(input('请输入第%位学生电话:'% x))
dict1 = {'name':new_name,'age':new_age,'score':new_score,'tel':new_tel}
all_studens.append(dict1)
print(all_studens)
1.添加学生:输入学生信息,将输入的学生的信息保存到all_students中
while True:
char = input('是否输入信息:')
if char == '是':
name = input('输入姓名:')
age = int(input('输入年龄:'))
score = int(input('输入成绩:'))
tel = int(input('输入电话:'))
dict1 = {'name':name,'age':age,'score':score,'tel':tel}
print(dict1)
例如输入:
姓名: 小明
年龄: 20
成绩: 100
电话: 111922
那么就在all_students中添加{'name':'小明', 'age': 20, 'score': 100, 'tel':'111922'}
2.按姓名查看学生信息:
例如输入:
姓名: stu1 就打印:'name':'stu1', 'age': 19, 'score':81, 'tel':'192222'
list1 = [
{'name':'stu1','age':18,'score':89,},
{'name':'stu2','age':28,'score':65,},
{'name':'stu3','age':23,'score':75,},
{'name':'stu4','age':25,'score':99,}
]
new_name = input('输入学生姓名:')
count = 0
for dict1 in list1:
if new_name == dict1['name']
print(dict1)
count += 1
if count == 0:
print('没有该学生')
3.求所有学生的平均成绩和平均年龄
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'},
]
new_age = 0
new_score = 0
for dict1 in all_studens:
age = dict1['age']
score = dict1['score']
new_age += age
new_score += score
avre_age = new_age / len(all_studens)
avre _score = new_score / len(all_studens)
print('所有学生的平均成绩为:%.1f,平均年龄:%.1f' % (avre_score,avre_age))
4.删除班级中年龄小于18岁的学生
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'},
]
for dict1 in all_students:
if dict1['age'] < 18:
dict1.clear()
print(all_students)
5.统计班级中不及格的学生的人数
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'},
]
num = 0
for dict1 in all_students:
if dict1['score'] <60:
num += 1
print('班级中不及格的学生的人数:%d' % num)
6.打印手机号最后一位是2的学生的姓名
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'},
]
for dict1 in all_students:
char = dict1['tel']
if char[-1] == '2':
print(dict1['name'])
网友评论