我有一个名为 Info 的类,其中 Info 有一个字符串类型的实例变量,可以通过Info.getName()
我还有一个实例信息列表,例如class_list = [Info('Aleck'), Info('John')]
.
给定 a name_list = ['Aleck', 'Bob']
,我想删除 class_list 中 name_list 中具有相同名称的元素,同时我还需要知道某个名称(例如 Bob)是否不在 class_list 中(例如打印出 bob 不在列表中)
对于上面的例子,结果应该是 class_list = [Info('John')] 并打印出 bob 不在列表中。
我知道这样做的丑陋方式,例如以下代码(我实际上并没有运行它,只是一个例子),是否有优雅或 Pythonic 的方式来做到这一点?
def removeElement(name_list, class_list):
list_to_be_removed = []
for name in name_list:
is_name_in_list = false
for obj in class_list
if name == obj.getName():
list_to_be_removed.add(obj)
is_name_in_list = true
break
if is_name_in_list == false:
print name + ' is not in the list'
is_name_in_list = false
for obj in list_to_be_removed:
class_list.remove(obj)