从列表中删除具有属性的对象?

时间:2020-01-07 14:03:18

标签: python list class object del

因此,我有一个具有属性[“ lname”,“ fname”,“ gender”,age]的对象列表,并且需要根据“ fname lname”的输入使用类析构函数来删除客户。当我尝试这样做时,我收到一条错误消息:“ TypeError:列表索引必须是整数或切片,而不是FitClinic”。我该如何解决?这是我到目前为止所拥有的:

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])) 

def bubblesort(listofcustomers):
    for i in range(len(listofcustomers)):
        for j in range(0, len(listofcustomers) -i -1):
            if listofcustomers[j].get_lname()>listofcustomers[j+1].get_lname():
                listofcustomers[j],listofcustomers[j+1] = listofcustomers[j+1],listofcustomers[j]
    return listofcustomers

def printlist():
    for c in listofcustomers:
        print("\t",c.get_lname(),c.get_fname(),c.get_gender(),c.get_age())

x=[]
x=input("Please enter the first and lastname of the customer you wish to remove: ")
x=x.split(" ")
for c in listofcustomers:
    if x[0] == listofcustomers[c].get_fname() and x[1] == listofcustomers[c].get_lname():
        del listofcustomers[c]
print("List of customers:")
bubblesort(listofcustomers)
printlist()

1 个答案:

答案 0 :(得分:0)

您正在使用for循环,因此每次为变量c分配一个FitClinic实例,因此您不能将其用作列表中的索引,这将起作用: / p>

for i,_ in enumerate(listofcustomers):
    if x[0] == listofcustomers[i].get_fname() and x[1] == listofcustomers[i].get_lname():
        del listofcustomers[i]