鉴于
这不仅仅是从列表中删除元素;删除但使用字段值
philani = Student(20, "Philani Sithole", "Male", [64,65])
sarah = Student(19, "Sarah Jones", "Female", [82,58])
fabian = Student(50, "Fabian Hamza", "Male", [50,52])
students = [philani, sarah, fabian]
如何从学生名单中删除对象fabian,名称为" Fabian Hamza"
期望的结果:
students = [philani, sarah]
尝试了这个
name = "Fabian Hamza"
for i in xrange(len(students)):
if hasattr(students[i], name):
students.pop(i)
但它不起作用
答案 0 :(得分:1)
您可以使用列表推导来实现:
[s for s in students if s.name != 'Fabian Hamza']
如果您只想要名单,请尝试:
[s.name for s in students if s.name != 'Fabian Hamza']