【问题标题】:How do I remove items from a list based off of class data如何根据类数据从列表中删除项目
【发布时间】:2022-11-19 11:15:02
【问题描述】:
class Student:

    def __init__(self, name, major, gpa, onProbation):
        self.name = name
        self.major = major
        self.gpa = gpa
        self.onProbation = onProbation

        Student1 = Student("Josh", "Business", 3.8, False)
        Student2 = Student("Maya", "Accountancy", 2.5, True)
        Student3 = Student("Dan", "Psychology", 1.2, True)
        Student4 = Student("Keon", "Biomedical Engineering", 4.0, False)
        Student5 = Student("Michelle", "Medicine", 3.7, False)
        Student6 = Student("Joey", "Law", 4.0, False)

Students = ["Josh", "Maya", "Dan", "Keon", "Michelle", "Joey"]

我想弄清楚如何从列表中删除所有处于试用期的学生,所以如果我输入 print(Students),它只会给我未处于试用期的学生(Josh、Keon、Michelle 和 Joey )

【问题讨论】:

  • 如果 Students 是实际的 Student 对象列表,而不是字符串,那会容易得多。

标签: python python-3.x list class


【解决方案1】:

我就是这样做的。当你创建类时,它甚至会记住列表中的属性分配。 cpython中有个叫pylist的


class Student:

    def __init__(self, name, major, gpa, onProbation):
        self.name = name
        self.major = major
        self.gpa = gpa
        self.onProbation = onProbation


student1 = Student("Josh", "Business", 3.8, False)
student2 = Student("Maya", "Accountancy", 2.5, True)
student3 = Student("Dan", "Psychology", 1.2, True)
student4 = Student("Keon", "Biomedical Engineering", 4.0, False)
student5 = Student("Michelle", "Medicine", 3.7, False)
student6 = Student("Joey", "Law", 4.0, False)

students = [student1,student2,student3,student4,student5, student6]


for index, student in enumerate(students):
    if student.onProbation:
        students.remove(students[index])

【讨论】:

    猜你喜欢
    • 2011-03-17
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多