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')
我认为您正在寻找:
object_list = filter(lambda x: x.name != 'some_name', object_list)
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']
if hasattr(my_object,"some_attribute") : doSomething()
尽管就您而言,我认为您想要
filter(lambda x:not hasattr(x,"name") or x.name != "some_name",my_list_of_objects)
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.