这是在Python 3.3中。
所以我有两个课程:Employee
和Zone
。 Zone
获取我创建的Employee
个对象,并将name
和ID
放入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()
完全感到困惑。
非常感谢任何帮助!
答案 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))