【问题标题】:Deleting an object with attributes from a list? [duplicate]从列表中删除具有属性的对象? [复制]
【发布时间】:2020-01-07 14:03:18
【问题描述】:

所以,我有具有属性 ["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()

【问题讨论】:

    标签: python list class object del


    【解决方案1】:

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

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

    【讨论】:

    • 在迭代时从容器中删除对象是一种非常糟糕的做法
    • @Marcos 抱歉,我还是 python 新手,枚举函数是做什么的?
    • @DeepSpace 它在我的项目要求中
    • @DeepSpace 你是对的。
    • @osmans enumerate 在每次迭代中给出索引和值。 docs.python.org/3/library/functions.html#enumerate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多