首页 > 解决方案 > 从列表中删除对象?

问题描述

所以我仍然是一个初学者程序员,他的任务是对由具有属性 lname、fname、性别、年龄(按此顺序)的 csv 文件创建的对象进行排序,并按 lname 属性对它们进行排序。我已经实现了这一点,但是我现在需要删除其中一个对象(我选择了一个随机对象进行测试),这就是我目前所拥有的:

class FitClinic:
    def __init__(self, lname, fname, gender, age):
        self.lname = lname
        self.fname = fname
        self.gender = gender
        self.age = int(age)

    def __del__(self):
        print("Customer has been deleted")

    def get_lname(self):
        return self.lname

    def get_fname(self):
        return self.fname

    def get_gender(self):
        return self.gender

    def get_age(self):
        return self.age

fh=open('fit_clinic_20.csv', 'r')
fh.seek(3)
listofcustomers=[]
for row in fh:
    c = row.split(",")
    listofcustomers.append(FitClinic(c[0], c[1], c[2], c[3]))

sorted_list=sorted(listofcustomers,key=lambda x: x.get_lname())

for x in sorted_list:
    if x.get_lname()==("Appleton"):
        del x
    print(x.get_lname(),x.get_fname(),x.get_gender(),x.get_age())

现在它显然不起作用,我需要一些帮助。

标签: pythoncsvsortingobjectdel

解决方案


del x just deletes the temporary variable x, it has no effect on the list. You need to use del listofcustomers[pos], but first you have to find the position in the list.

try:
    pos = next(i for i,v in enumerate(listofcustomers) if v.get_lname() == "Appleton")
    del listofcustomers[pos]
except StopIteration:
    pass // Ignore if not found

See Python: return the index of the first element of a list which makes a passed function true for numerous ways to find the index of an element that matches a criteria.


推荐阅读