python - 从列表中删除对象?
问题描述
所以我仍然是一个初学者程序员,他的任务是对由具有属性 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())
现在它显然不起作用,我需要一些帮助。
解决方案
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.
推荐阅读
- mysql - 如何查询我的表以按 mySQL 中的 2 个字段对其进行分组?
- .net-core - 我们如何更改发布配置以根据设置发布不同版本的文件
- arrays - Kotlin - 遍历数组
- android - 无法访问“androidx.activity.result.ActivityResultCaller”
- actions-on-google - 为 NodeJS 初始化 Google Actions SDK 后更新 clientId
- php - 如何使用 bootstrap 4 modal 创建日期过滤器过滤器
- c# - 是否有一个测试数据构建器可以处理没有默认构造函数的类?
- r - 将函数应用于小标题的每个案例
- mongodb - MongoDB聚合查询优化:match -> unwind -> match vs unwind->match
- vb.net - mciSendString,将 VB 脚本移植到 CE Lua 脚本