我有这个输出并希望删除特定的用户词典但显然,我的代码只删除了附加到列表的最后一个用户,即使在指定要删除的内容之后。非常感谢帮助。
[{'password': '1234', 'id': 1, 'name': 'martin'}, {'password': '123',
'id': 2, 'name': 'artin'}, {'password': '134', 'id': 3, 'name':
'tin'}, {'password': '1234', 'id': 4, 'name': 'mart'}]
如何删除{'password': '123', 'id': 2, 'name': 'artin'}
这是我的代码:
class ClassRoom:
def __init__(self):
self.people= []
self.id = 0
def get_people(self):
return self.people
def add_person(self, name, password):
self.id += 1
self.user = {
'id': self.id,
'name': name,
'password': password,
}
self.people.append(self.user)
def remove_person(self, name, password):
self.id -= 1
if self.user in self.people:
if self.user['name'] and self.user['password']:
self.user.clear()
if __name__ == '__main__':
room = ClassRoom()
room.add_person('martin','1234')
room.add_person('artin','123')
room.add_person('tin','134')
room.add_person('mart','1234')
print("before remove", room.get_people())
room.remove_person('artin', '123')
print("after remove", room.get_people())
答案 0 :(得分:1)
如果我错了,请纠正我,但是通过查看你的代码,你将字典(单个人)传递给列表,这样就可以简单地删除列表中的条目(整个字典,或者人与)
self.people.pop()
或
self.people.remove(index).
我希望这会对你有所帮助
答案 1 :(得分:0)
显然,我想通了。
def remove_person(self, id):
self.id = id
for self.user in range(len(self.people)):
if self.people[self.user]['id'] == self.id:
del self.people[self.user]
break