Reputation: 3350
We have some objects with properties
class my_object:
def __init__(self, type, name):
self.type = type
self.name = name
And a list which contains many object with different type
and name
values.
What I need is a comprehension which does something like:
if my_object.type == 'type 1' in object_list:
object_list.remove(all objects with name == 'some_name')
Upvotes: 1
Views: 532
Reputation: 6430
You could do:
def remove_objects(obj_list,*args,**kwargs):
for n_count,node in enumerate(obj_list[::]):
del_node=False
for k,v in kwargs.items():
if hasattr(node,str(k)):
if getattr(node,str(k))==v:
del_node=True
break
if del_node:
del obj_list[n_count]
And use it like:
class HelloWorld(object):
lol="haha"
my_list_of_objects=[HelloWorld for x in range(10)]
remove_objects(my_list_of_objects,lol="haha")
Upvotes: 0
Reputation: 309831
I think you are looking for:
object_list = filter(lambda x: x.name != 'some_name', object_list)
Upvotes: 2
Reputation: 6828
I think what you need is :
if any(obj.type == 'type 1' for obj in object_list):
object_list = [obj for obj in object_list if obj.name != 'some_name']
Upvotes: 2
Reputation: 113940
if hasattr(my_object,"some_attribute") : doSomething()
although in your case I think you want
filter(lambda x:not hasattr(x,"name") or x.name != "some_name",my_list_of_objects)
Upvotes: 0