标签:key 要求 pen zha [] import for 个学生 字典列表
第一题
class Stu:
# 设置学生基础属性
def __init__(self, name, num, age, cj):
self.name = name
self.num = num
self.age = age
self.cj = cj
def __str__(self):
return ‘姓名:{},学号:{},年龄:{},成绩{}‘.format(self.name, self.num, self.age, self.cj)
# 查看学生类是否创建成功
# c = Stu(‘小米‘, 100, 18, 66)
# print(c)
class Class1:
def __init__(self, name):
self.name = name
self.class_dict = {}
self.class_list = []
def add_stu(self, stu):
# 添加学生至对应字典列表
self.class_dict[stu.num] = stu
self.class_list.append(stu)
def del_stu(self, num):
# 弹出后删除
stu_danchu = self.class_dict.pop(num)
self.class_list.remove(stu_danchu)
def sort_stu(self, key, reverse=False):
# 排序
self.class_list.sort(key=key, reverse=reverse)
def show_class(self):
# 打印
print(self.name)
for i in self.class_list:
print(i)
def chazhao_stu(self, num):
return print(self.class_dict.get(num))
# 测试代码
import random
c1 = Class1(‘python‘)
for i in range(10):
name = ‘stu‘ + str(i)
num = 100 + i
age = random.randint(18, 25)
cj = random.randint(70, 100)
c = Stu(name, num, age, cj)
c1.add_stu(c)
# 展示
c1.show_class()
# 排序
c1.sort_stu(key=lambda s: s.num, reverse=True)
# 查找
c1.chazhao_stu(108)
# 删除
c1.del_stu(109)
c1.show_class()
标签:key 要求 pen zha [] import for 个学生 字典列表
原文地址:https://www.cnblogs.com/wenjiangtao/p/10546956.html