搜索包含类对象的列表,并删除与类对象的实例变量匹配的类对象

时间:2015-11-08 22:27:28

标签: python python-3.x

这是在Python 3.3中。

所以我有两个课程:EmployeeZoneZone获取我创建的Employee个对象,并将nameID放入list。我希望remove_employee方法将员工ID放入字符串中,找到与ID匹配的员工,然后将其从列表中删除。这就是我到目前为止所拥有的:

class Employee:
employee_count = 0

    def __init__(self, name, employee_id):
        self._name = name
        self._employee_id = employee_id
        Employee.employee_count += 1

    def get_employee_id(self):
        return self._employee_id


class Zone:

    def __init__(self, name="Kitchen", employees=[]):
        self._name = name
        self._employees = employees

    def add_employee(self, employee):
        self._employees += [employee]

    def remove_employee(self, employee_id):
        for employee_id in self._employees:
            self._employees.remove(employee_id)

    def number_of_employees(self):
        return len(self._employees)

当我尝试运行时:

John = Employee('John', 'F12345')
Jack = Employee('Jack', 'F23514')
Jane = Employee('Jane', 'F10253')
Kitchen = Zone()
Kitchen.add_employee(John)
Kitchen.add_employee(Jack)
Kitchen.add_employee(Jane)
Kitchen.remove_employee('F12345') #John's ID

它从列表中删除了John和Jane,而不仅仅是John。我对编程非常陌生,而且我对如何编写remove_method()完全感到困惑。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

remove_employee中,您实际上并未检查员工ID是否与循环中的当前值匹配。此外,您不应该修改您正在迭代的列表;它可能会导致各种各样的问题。好像你想要这样的东西:

def remove_employee(self, employee_id):
    employees = []
    for employee in self._employees:
        if employee._employee_id != employee_id:
            employees.append(employee)
    self._employees = employees

可以通过名为列表理解的东西显着缩短:

def remove_employee(self, employee_id):
    self._employees = [e for e in self._employees if e._employee_id != employee_id]

但是,如果你使用适当的数据结构来存储员工,这是一个dict,由ID键入,而不是列表,那么整个过程会更简单。例如:

class Zone:
    def __init__(self, name="Kitchen", employees=None):
        self._name = name
        self._employees = employees or {}

    def add_employee(self, employee):
        self._employees[employee._employee_id] = employee

    def remove_employee(self, employee_id):
        self._employees.pop(employee_id)

    def number_of_employees(self):
        return len(self._employees)

答案 1 :(得分:0)

问题是您正在使用

迭代员工列表

for self._employees中的employee_id

并删除员工。

你应该改变做这样的事情:

def remove_employee(self, employee_id):
    for employee in self._employees:
        if employee.get_employee_id() == employee_id:
            self._employees.remove(employee)

或更好的过滤! =)

def remove_employee(self, employee_id):
        self.employees = list(filter(lambda x: x.get_employee_id() != employee_id))