美文网首页
python类比C语言结构体更方便

python类比C语言结构体更方便

作者: AibWang | 来源:发表于2020-12-24 18:32 被阅读0次

    定义一个StudentNode类,将其用于存储一个学生的信息

    # arrival time table class
    class StudentNode:
        def __init__(self, name, gender, math_score, physics_score)
            self.name = name
            self.gender = gender
            self.math_score = math_score
            self.physics_score = physics_score
    #
    

    那么一个以StudentNode类为元素的列表就可以用来存储整个班级学生的信息。

    建立学生列表:

        student_list = []
        student_list.append(StudentNode(name='Zhangsan', gender='male', math_score=78.5, physics_score=88))
        student_list.append(StudentNode(name='Lisi', gender='female', math_score=96, physics_score=87))
    

    借助列表的sort方法,一行代码就可以实现排序:

        # 根据学生的math_score从大到小排序
        student_list.sort(key=lambda x_student: x_student.math_score, reverse=True)
        for istudent in range(len(student_list)):
            print("%s  math score:%.1f" % (student_list[istudent].name, student_list[istudent].mathscore))
    

    相关文章

      网友评论

          本文标题:python类比C语言结构体更方便

          本文链接:https://www.haomeiwen.com/subject/hpzmnktx.html